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

Adding items in the nested array of React state

I’m trying to add new items to an array of an object that resides in another object of a state. Pretty nested.

So I tried the following way…

// The initial data
[options, setOptions] = useState({
    name: 'Name goes here'
    type: 'type goes here'
    series : [{
        type: 'series type',
        label: 'series label'

})

Now I want to add another object inside the object of series array with useEffect(). And I tried:

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

useEffect(() => {
    // other functionalities goes here
    setOptions({
        ...options, // for copying previous data outside of series
        series: [{
            ...options.series, //this is for copying previous data of series
            tooltip: {
                enable: true,
        }]
    })
}, [refreshData])

The way I’m copying ...options works absolutely fine, But when I try to copy ...options.series it adds a new copied object inside the object of series array like the following:

{
    name: 'Name goes here' //fine
    type: 'type goes here' //fine
    series: [{
        {type: 'series type', label: 'series label'}, //not fine
        tooltip: {enable: true} //not fine
        //what I want is: to have previous object data and tooltip appended as another item
    }]
}

The way I want the object to be is:

{
    name: 'Name goes here' //fine
    type: 'type goes here' //fine
    series: [{
        type: 'series type', 
        label: 'series label'
        tooltip: {enable: true}
    }]
}

Can Anybody help me regarding this. I would appreciate any help..
Thanks

>Solution :

here is sample of what you are trying to achieve .

const d = {
    name: 'Name goes here',
    type: 'type goes here',
    series : [{
        type: 'series type',
        label: 'series label'
  }]
}


const newD = {
    ...d,
    series: [
        {
          ...d.series[0], // problem is here
          tooltip: {
            enable: true,
          }
        }
      ]
  } 
console.log (newD)
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