I’m trying to add a new element to the tree by id. I’m using recursion for this. My attempt
const treeData = [{
title: 'parent 1',
key: '0-0',
children: [{
title: 'parent 1-0',
key: '0-0-0',
disabled: true,
children: [{
title: 'leafffff',
key: '0-0-0-0',
}
],
}, ],
}, ];
const recursiveUpdate = (data, key) => {
return data.reduce((acc, el) => {
if (el.key === key) {
acc.push({
...el,
children: [
...el.children || [],
{
title: '111111111111',
key: 'new-key'
},
],
});
} else if (el.children) {
recursiveUpdate(el.children, key);
}
return acc;
}, []);
}
console.log(recursiveUpdate(treeData, '0-0-0'));
This function only works at the nesting level. Help me with this problem
2
Answers
You should add your non-matched elements too:
Btw you don’t need
Array:reduce()
here. TheArray:map()
is enough and it’s faster:But the problem is the OP commented that he/she wants to MODIFY the existing data though his code definitely creates a copy. So for modifying the existing data, we could just find a needed node to modify and add an extra child:
And a benchmark of map vs reduce: