Home > other >  Unable to set a dynamic value to predefined object in typescript
Unable to set a dynamic value to predefined object in typescript

Time:12-27

I want to store a dynamic id every time in the array of object format

Suppose I have 3 ids one is id = 250 and the second one is id = 650 and the third one is id = 850

and

I want to store it like

[
{
 id:250,
 how_many_times = 1
},
{
 id:650,
 how_many_times = 2
},
{
 id:850,
 how_many_times = 1
}
]

But when I tried to set the id it's showing me this error

Property 'id' does not exist on type '{ id: string; }[]'

I have tried the following lines of code

first I created an array like this

popUpShowData = [
    {
      id : '',
      how_many_times:0
    }
 ];

then I tried to set the value like this

getPopup(dynamicId) {
   this.popUpShowData.id = dynamicId;
   this.popUpShowData.how_many_times = 1;
}

but getting this error

Property 'id' does not exist on type '{ id: string; }[]'

CodePudding user response:

popUpShowData is an array, so you have to set the id property to one of its items, not on it directy:

this.popUpShowData[0].id = dynamicId;
this.popUpShowData[0].how_many_times = 1;

In general, you should in addition pass the index of the item to the function, so you would know which item to update:

getPopup(index, dynamicId) {
  this.popUpShowData[index].id = dynamicId;
  this.popUpShowData[index].how_many_times = 1;
}
  • Related