This is my data structure:
const data = [
{
id: 'root',
name: 'root',
children: [
{
id: 'childA',
name: 'childA',
children: []
},
{
id: 'childB',
name: 'childB',
children: [
{
id: 'childB_A',
name: 'childB_A',
children: [
{
id: 'childB_A_A',
name: 'childB_A_A',
children: []
},
{
id: 'childB_A_B',
name: 'childB_A_B',
children: []
}
]
}
]
}
]
}
]
Now let's say I select childB_A_A
, this means the path to it is as follows root > childB > childB_A > childB_A_A
or with indexes 0 > 1 > 0 > 0
/ root[0].children[1].children[0].children[0]
This is the function I have now.
function findItem(children, indexes, item) {
if (indexes.length <= 0) {
return item
}
const [currPos] = indexes.splice(0, 1)
const currItem = children[currPos]
return findItem(currItem.children, indexes, currItem)
}
This is how I'm calling the function findItem(data, [0, 0])
(selecting childA
)
It successfully finds the item I'm searching. But that's not all I need, I also need to remove all children from the siblings of the found item.
So if I now have childB_A_A
selected and I select childA
then childB
's children need to be set to an empty array.
And I either need to mutate in place or return the new structure like this:
const data = [
{
id: 'root',
name: 'root',
children: [
{
id: 'childA',
name: 'childA',
children: []
},
{
id: 'childB',
name: 'childB',
children: []
}
]
}
]
I have tried using different approaches like passing the id
instead of the indexes path & recursively filtering the children like shown in this StackOverflow answer but it removes the sibling and I want to mutate it.
So yeah essentially what I need to do is:
- traverse nested array
- find item
- change all siblings to have an empty array
- return changed nested array