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.
// 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',
}],
}];