Home > Software engineering >  How to check and change value of properties in object with typescript using loop?
How to check and change value of properties in object with typescript using loop?

Time:08-08

I've checked some answers related to iterating or looping through, which I've managed to do it, but the problem is, I can't change value of property.

Here's the code :

export interface BaseOnTotalPaidFields {
    groupName: string,
    minimumTotalPaid: string,
    havePointBonus: boolean,
    pointBonus: string,
    rewardType: string,
    rewardBonus: string,
    haveReward: boolean,
    rewardPeriod: string,
}
const editMode: ComputedRef<ClubDialogEditMode> = computed(() => store.state.serviceModule.clubDialogs.vipConfigurationDialog.editMode)

let data = editMode.value.form.groupFields as BaseOnTotalPaidFields
// Or
let data : BaseOnTotalPaidFields = editMode.value.form.groupFields as BaseOnTotalPaidFields

Object.entries(data).forEach(([key, value])=> {
    console.log(key)
    console.log(value)
    if (value == null) {
        // Below line giving error
        data[key]  =  ''
    }
})

Base on above code, I'm getting below error :

TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'BaseOnTotalPaidFields'.   No index signature with a parameter of type 'string' was found on type 'BaseOnTotalPaidFields'.

I've also tried below code and again, didn't worked :

  for (const [k, v] of Object.entries(data)) {
    // Same Error.
    data[key]  =  ''
  }

Tried a few more solutions base on search and didn't worked.

CodePudding user response:

You could change the definition of your interface as follow : export interface BaseOnTotalPaidFields extends Record<string,any> {

Playground

  • Related