[英]How to update nested object of array of objects in Javascript?
const testArr = [
{ id: 'aaa',
children: [
{ id: 'aaa-1',
children: [
{ id: 'aaa-1-1' }
]
},
{ id: 'aaa-2'}
]
},
{ id: 'bbb' },
]
I am having nested array of objects to managa my redux
store. 我有嵌套的对象数组managa我的
redux
商店。 I want to add new property to object. 我想向对象添加新属性。 Let's add
children
to id: aaa-2
, the object will be below: 让我们将
children
项添加到id: aaa-2
,对象将在下面:
const testArr = [
{ id: 'aaa',
children: [
{ id: 'aaa-1',
children: [
{ id: 'aaa-1-1' }
]
},
{ id: 'aaa-2',
children: [{ someNewKey: 'someNewValue' }]
}
]
},
{ id: 'bbb' },
]
Is there a way to update nested level of object with specific key:value pair? 有没有办法用特定的键:值对更新嵌套的对象级别? I try to make function, but it's not working well
我尝试制作功能,但效果不佳
I tried // but it's not working properly when try to inner updates 我试过//但是在尝试内部更新时它无法正常工作
const updateDeep = (arr, id, push) => {
return arr.map(el => {
if (el.id === id) {
return Object.assign({}, el, { children: push })
}
else {
if (el.children) {
return updateDeep(el.children, id, push)
} else {
return el
}
}
})
}
Resolve it myself 自己解决它
function updateDeep(array, id, newObj) {
array.some((o, i) => {
var temp;
if (o.id === id) {
o.children = [...(o.children ? o.children : []), newObj]
}
if (temp = updateDeep(o.children || [], id, newObj)) {
o.children = [...(o.children ? o.children : []), newObj]
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.