const testArr = [
{ id: 'aaa',
children: [
{ id: 'aaa-1',
children: [
{ id: 'aaa-1-1' }
]
},
{ id: 'aaa-2'}
]
},
{ id: 'bbb' },
]我有嵌套的对象数组到managa我的redux商店。我想向对象添加新属性。让我们将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' },
]有没有一种方法可以用特定的键更新嵌套级别的对象:值对?我试着发挥作用,但效果不太好
我试过//,但是当尝试内部更新时,它不能正常工作
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
}
}
})
}发布于 2019-06-18 04:38:52
自己解决
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]
}
});
}https://stackoverflow.com/questions/56640078
复制相似问题