I'm using ReactJs where I need to search in array of objects
Here is array
const menuList = [
{
title: "Top 1",
link: "top1",
},
{
title: "Top 2",
link: "top2",
children: [
{
title: "Top 2",
link: "top2",
parent: true
},
{
title: "Top 2 child 1",
link: "top2-child-1",
},
{
title: "Top 2 children 2",
link: "top2-child-2",
children: [
{
title: "deep nested child",
link: "deep-nested-child"
}
]
},
{
title: "Top 2 child 2",
link:"top2-child-2"
},
{
title: "Top 2 child 3",
link: "top2-child-3",
children: [
{
title: "Nested child of Child 3",
link: "nested-child-of-3"
}
]
}
]
}
];
I want to search based on link But I want to search first in deep children then the top one. Search start from the deepest children and go to top until it find the match. If no match found it will return the same menuList back. If any match found then I want to get back whole array of this level not the single object.
For example if I search top2-child-1 then it should return.
[
{
title: "Top 2",
link: "top2",
parent: true
},
{
title: "Top 2 child 1",
link: "top2-child-1",
},
{
title: "Top 2 children 2",
link: "top2-child-2",
children: [
{
title: "deep nested child",
link: "deep-nested-child"
}
]
},
{
title: "Top 2 child 2",
link:"top2-child-2"
},
{
title: "Top 2 child 3",
link: "top2-child-3",
children: [
{
title: "Nested child of Child 3",
link: "nested-child-of-3"
}
]
}
]
What I'm trying is here.
const find_nested_link = (menuList, path) => {
for (let i = 0; i < menuList.length; i++) {
if (menuList[i].children) {
return find_nested_link(menuList[i].children, path);
} else {
if (menuList[i].link === path) {
return menuList;
}
}
}
};
It will work only for first deep nested child. if you search nested-child-of-3 it will not able to find it.
Here is another one which is also not work perfect.
const result = menuList.reduce((r, { children }) => {
let o = children.filter(({ link }) => link === path);
if (o && o.length) r.push(...children);
return r;
}, []);