I have an array of tree structures. I need to be able to find the object using the index paths and update the toggle boolean. I am able to update the toggle using the index path, but this logic will need to be updated if more levels of nodes are added to the tree. How can I make it generic, so my code still works even if the treeData is changed?
It’d be nice if I can set all other nodes false if it is in not in the one of the index paths.
treeData = [{
name: 'Infiniti',
toggle: false,
children: [{
name: 'G50',
toggle: false,
children: [{
name: 'Pure AWD',
toggle: false
},
{
name: 'Luxe',
toggle: false
},
],
},
{
name: 'QX50',
toggle: false,
children: [{
name: 'Pure AWD',
toggle: false
},
{
name: 'Luxe',
toggle: false
},
],
},
],
},
{
name: 'BMW',
toggle: false,
children: [{
name: '2 Series',
toggle: false,
children: [{
name: 'Coupé',
toggle: false
},
{
name: 'Gran Coupé',
toggle: false
},
],
},
{
name: '3 Series',
toggle: false,
children: [{
name: 'Sedan',
toggle: false
},
{
name: 'PHEV',
toggle: false
},
],
},
],
},
];
indexPathArray = ["0/0/1", "1/0/0"]
for (const index of indexPathArray) {
const indexArray = index.split('/')
for (let i = 0; i < indexArray.length; i++) {
if (i === 0) {
treeData[indexArray[0]].toggle = true;
}
if (i === 1) {
treeData[indexArray[0]].children[indexArray[1]].toggle = true;
}
if (i === 2) {
treeData[indexArray[0]].children[indexArray[1]].children[indexArray[2]].toggle = true;
}
}
}
console.log(treeData);