I want to be able to remove an object from an array of objects that have children. I thought immediately this is a job for recursion, but I am unable to get my recursion function to work properly. I thought of using reduce to rebuild the data structure without the object that I want to remove. The function should accept two parameters the array of nested objects and an Id.
My requirements are: remove the node and all children below.
At first glance, this seems easy, but the challenge I find is removing a child and keeping the entire data structure intact. Deleting the parent by filtering based on the id is trivial, but the nested children pose a problem.
My data structure looks like this:
const data = [{
id: 'BFQEA1W2RK1YRETZ9343',
name: 'Cover',
activityId: 'BFQEA1W2RK1YRETZ9343',
nodeType: 'activity',
suppressed: true,
hidden: true
},
{
children: [
{
id: 'ZNRAE749BSD0CTGHY888',
name: 'Consultants, Reviewers, and National Geographic Exploration',
activityId: 'ZNRAE749BSD0CTGHY888',
nodeType: 'activity',
suppressed: false,
hidden: false
},
{
id: 'JZLS37EVZQM22H9Q4655',
name: 'The National Geographic Approach',
activityId: 'JZLS37EVZQM22H9Q4655',
nodeType: 'activity',
suppressed: false,
hidden: false
},
]
}
]
If I pass this Id(ZNRAE749BSD0CTGHY888) to the function my expected data result should be:
const expected = [{
id: 'BFQEA1W2RK1YRETZ9343',
name: 'Cover',
activityId: 'BFQEA1W2RK1YRETZ9343',
nodeType: 'activity',
suppressed: true,
hidden: true
},
{
children: [
{
id: 'JZLS37EVZQM22H9Q4655',
name: 'The National Geographic Approach',
activityId: 'JZLS37EVZQM22H9Q4655',
nodeType: 'activity',
suppressed: false,
hidden: false
},
]
}
]
My function looks like this:
findNode = (id, arr) => {
return arr.reduce((a, item) => {
// if (item.id === id) {
// console.log('here');
// return item;
// }
if (item.id !== id) {
a.push(item);
}
if (item.children) {
return this.findNode(id, item.children);
}
}, []);
};
The function's reduce accumulator is undefined, but I am unsure why. It should be making a new array. What am I missing here?
In my head, this seems to work, but it fails. Maybe my approach is completely off. How should I go about solving this?