I am working with an object structure that looks like this:
const obj = {
name: 'john',
children: [
{
name: 'Foo'
},
{
name: 'Bar',
children: [
{
name: 'Doe'
}
]
}
]
}
My task is to create a function that can locate and return the object with a specified name. Currently, my code is able to find objects by name, but it does not successfully return the located object.
const search = (node, name) => {
return searchInObj(node, name);
};
const searchInObj = (obj, name) => {
if (obj.name === nodeName) {
return obj;
} else {
if (obj.children) {
searchInArr(obj.children, name);
}
}
};
const searchInArr = (arr, name) => {
for (let i = 0; i < arr.length; i++) {
searchInObj(arr[i], name);
}
};
When I test it with
console.log(search(obj, 'Doe')) // returns undefined
The function only works as expected when searching for john