Home > other >  How to update Nested object in array -react
How to update Nested object in array -react

Time:01-23

I am trying to update the properties (array of objects). I have to update the complete object with new given object

writing an test case in which i need to update specific prop1.B values to prop2 values but i am not able to do this

const prop1 = {
mainList:{
list1:[{...}],
list2:[{...}],
list3:[...]
  }
}

to

const prop2 = {
list2:[{...}],
}

i want to update prop1.mainList.list2 values to prop2.list2 values

My work around on this issue

   const { output } = renderList({...prop1,...prop1.mainList.list2,...prop2,...prop2.list2})

list2 is not updating

CodePudding user response:

Are you trying to update prop1.mainList.list2 with the contents of prop2.list2? If so, you can do something like this:

{mainList: {...prop1.mainList, ...prop2}}

And if you want to add the contents of prop2.list2 to prop1.mainList.list2 you can do:

{mainList: {...prop1.mainList, list2: [...prop1.mainList.list2, ...prop2.list2]}}

A tip: for updating nested element like this one, use something like ImmerJS. It'll make your life way easier.

  • Related