简体   繁体   中英

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. I want to add new property to object. Let's add children to id: aaa-2 , the object will be below:

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]
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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