Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to set a dynamic value to predefined object in typescript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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; }[]'

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading