嵌套级别总是未知的,子级可以是未定义的,也可以是包含至少一个项的数组。每个键都是唯一的。这将是一个例子:
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',
}],
}];我想编写一个函数,它接收一个键来查找元素,然后用给定的子数组更新它的子字段,然后返回整个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',
}],
}];发布于 2022-07-11 19:06:31
这可以通过递归来实现。
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;
};https://stackoverflow.com/questions/72943377
复制相似问题