繁体   English   中英

如何在Javascript中更新对象数组的嵌套对象?

[英]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' },
]

我有嵌套的对象数组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
            }
        }
    })
}

自己解决它

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.

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