I have a nested data structure, and I want to create a recursive function that, given an object's name parameter, will return the parent object's name paramter.
There are several related questions, however, the answers don't explain why my function getParentName
isn't working.
Why is getParentName
not working?
const nestedData = {
name: "parent",
children: [{ name: "child", children: [{ name: "grandchild" }] }],
};
function getParentName(nested, name) {
if (nested.children && nested.children.map((d) => d.name).includes(name)) {
return nested.name;
} else if (nested.children) {
nested.children.forEach((child) => {
return getParentName(child, name);
});
}
return undefined; //if not found
}
//The parent of "grandchild" is "child" - but the function returns undefined
const parentName = getParentName(nestedData, "grandchild");
Why does this function not find the parent?