簡體   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