简体   繁体   English

如何更新数组中的嵌套 object -react

[英]How to update Nested object in array -react

I am trying to update the properties (array of objects).我正在尝试更新属性(对象数组)。 I have to update the complete object with new given object我必须用新的 object 更新完整的 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编写一个测试用例,其中我需要将特定的 prop1.B 值更新为 prop2 值,但我无法执行此操作

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

to

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

i want to update prop1.mainList.list2 values to prop2.list2 values我想将 prop1.mainList.list2 值更新为 prop2.list2 值

My work around on this issue我在这个问题上的工作

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

list2 is not updating list2 没有更新

Are you trying to update prop1.mainList.list2 with the contents of prop2.list2 ?您是否尝试使用prop1.mainList.list2的内容更新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:如果你想将prop2.list2的内容添加到prop1.mainList.list2你可以这样做:

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

A tip: for updating nested element like this one, use something like ImmerJS .提示:要更新像这样的嵌套元素,请使用类似ImmerJS的东西。 It'll make your life way easier.它会让你的生活更轻松。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM