I am faced with a complex JavaScript object structure that represents hierarchical data. This object contains multiple levels of nested children, and I have the task of searching for a specific value within this intricate structure. Let's take a look at an example of such a nested object:
const data = {
id: 1,
name: "Root",
children: [
{
id: 2,
name: "Child 1",
children: [
{
id: 3,
name: "Grandchild 1",
children: []
},
{
id: 4,
name: "Grandchild 2",
children: []
}
]
},
{
id: 5,
name: "Child 2",
children: [
{
id: 6,
name: "Grandchild 3",
children: []
}
]
}
]
};
Currently, I have implemented a recursive function to search for a particular value based on its ID:
function searchById(node, id) {
if (node.id === id) {
return node;
}
if (node.children) {
for (let child of node.children) {
const result = searchById(child, id);
if (result) {
return result;
}
}
}
return null;
}
const result = searchById(data, 4);
console.log(result);