I have a deeply nested JavaScript object structure representing a hierarchical data model. The object can have multiple levels of nested children, and I need to search for a specific value within this structure. Here is 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’m using a recursive function to search for the value by 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);