I have a recursive function, that removes an item by id, also if this item is nested in a children array, it will move it up one level, it's basically a sort of menu structure. When an item get's deleted, the children don't get thrown away, but stay in the original object.
Now this takes a 'data' parameter and manipulates it, but I'm wondering if it's possible to transform this into a function that returns a brand new array, keeping the argument immutable?
This is the function
function removeId(data, id, parent = null) {
data.forEach((o, i) => {
if (o.id && o.id === id) {
if (parent) {
o.children.forEach(c => parent.children.push(c));
}
data.splice(i, 1);
return true;
} else if (o.children) {
removeId(o.children, id, o);
}
});
}
This is the test data used
const data = [
{
id: 2,
children: [
{
id: 1,
children: []
}
]
},
{
id: 3,
children: [],
}
]
The function is called like this
data = removeId(data, itemIdToDelete)
The expected output is a new (immutable) array with the structure of the previous one, except the removed items (nested)
This is the expected output after running the method and passing the id of 2 to be deleted
const data = [
{
id: 1,
children: []
},
{
id: 3,
children: [],
}
]
I've tried
- Converting the function using Array.reduce() or Array.filter() but it breaks the recursiveness and returns undefined every time.
Edit: This is not just a simple deep cloning issue, there's logic involved, for example checking if a parent has children.