简体   繁体   English

JavaScript - 使用目标路径更新深度嵌套的对象数组

[英]JavaScript - update deeply nested array of objects with the target path

The nesting level is always unknown, and children can be either undefined or an array with at least one item.嵌套级别始终是未知的,子级可以是未定义的,也可以是包含至少一项的数组。 Each key is always unique.每个键始终是唯一的。 This would be an example:这将是一个例子:

const arr = [{
    key: '001',
    children: [{
        key: 'abc',
        children: [{
            key: 'ee',
            children: [{
                key: 'goc',
            }, {
                key: 'zzv',
                children: [{
                    key: '241',
                }],
            }],
        }],
    }, {
        key: '125',
        children: undefined,
    }],
}, {
    key: '003',
    children: [{
        key: 'ahge',
    }, {
        key: '21521',
    }],
}];

I'd like to write a function that receives a key to find the element and then updates its children field with the given children array and then returns the whole arr.我想编写一个函数,它接收一个键来查找元素,然后用给定的 children 数组更新它的 children 字段,然后返回整个 arr。

// Function that returns arr with updated the target element - how can I write this?
const mysteryFn = (arr, key, childrenToUpdate) => {
 // Do something..

 return arr;
}


const key = 'goc';
const childrenToUpdate = [{
 key: '12345',
}, {
 key: '25221a',
}];

const newArr = mysteryFn(arr, key, childrenToUpdate);

// expected newArr
const newArr= [{
    key: '001',
    children: [{
        key: 'abc',
        children: [{
            key: 'ee',
            children: [{
                key: 'goc',
                children: [{
                    key: '12345',
                }, {
                    key: '25221a',
                }],
            }, {
                key: 'zzv',
                children: [{
                    key: '241',
                }],
            }],
        }],
    }, {
        key: '125',
        children: undefined,
    }],
}, {
    key: '003',
    children: [{
        key: 'ahge',
    }, {
        key: '21521',
    }],
}];

This can be achieved with recursion.这可以通过递归来实现。

const mysteryFn = (arr, key, childrenToUpdate) => {
    // if children are undefined
    if (!arr) return;

    // loop over each entry and its children to find 
    // entry with passed key
    arr.forEach((entry) => {
        if (entry.key === key) {
            entry.children = childrenToUpdate;
        }

        // recursive call to traverse children
        mysteryFn(entry.children, key, childrenToUpdate);
    });

    return arr;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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