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

Update react State array of nested objects

Maybe this is stupid but my state is an array of nested objects 😮
It looks as follows:

  const data = [
        {
            randomid1: {
                name: 'lorem',
                latinName: 'ipsem',
            },
        },
        {
            randomid2: {
                name: 'lorem2',
                latinName: 'ipsem2',
            },
        },
    ]

I need to update this array with a new name and/or latinName for one of the items (let’s say randomid1.name .

I have been struggling with spreading etc but keep getting errors. Now im trying mapping over something but this too won’t work. Anyone?

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

>Solution :

You can check if the array contains a certain item using Array#find and Object#hasOwnProperty:

const 
  data = [
    { randomid1: { name: 'lorem', latinName: 'ipsem' } },
    { randomid2: { name: 'lorem2', latinName: 'ipsem2' } }
  ],
  id = 'randomid2';

const elem = data.find(e => e.hasOwnProperty(id));
if(elem) {
  elem[id].name = 'new name';
}

console.log(data);
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