I'm sure someone can explain this to me but even though the below function, see Main Code, finds the correct data it somehow returns the wrong data?
The return I get is
{
name: 'section 3',
sectionParentName: 'ROOT',
sectionChildren: [
{
name: 'section 3.1',
sectionParentName: 'section 3',
sectionChildren: [Array]
},
{
name: 'section 3.2',
sectionParentName: 'section 3',
sectionChildren: []
}
]
}
If I console.log(found)
I get what I'm looking for
[
{
name: 'section 3.1.2.1',
sectionParentName: 'section 3.1.2',
sectionChildren: []
},
{
name: 'section 3.1.2.2',
sectionParentName: 'section 3.1.2',
sectionChildren: []
}
]
In fact, the only reason I have 'const found' instead of just 'return section.sectionChildren' is because changing 'section.sectionChildren' to 'section.name' did nothing to the return data as a test? At least when assigning 'section.sectionChildren' to 'const found' and console logging it out I could see it contained the correct data.
Main Code
const MenuRoot = [
{
name: "section 1",
sectionParentName: "ROOT",
sectionChildren: [
{
name: "section 1.1",
sectionParentName: "section 1",
sectionChildren: [],
},
{
name: "section 1.2",
sectionParentName: "section 1",
sectionChildren: [],
},
],
},
{
name: "section 2",
sectionParentName: "ROOT",
sectionChildren: [
{
name: "section 2.1",
sectionParentName: "section 2",
sectionChildren: [],
},
{
name: "section 2.2",
sectionParentName: "section 2",
sectionChildren: [],
},
],
},
{
name: "section 3",
sectionParentName: "ROOT",
sectionChildren: [
{
name: "section 3.1",
sectionParentName: "section 3",
sectionChildren: [
{
name: "section 3.1.1",
sectionParentName: "section 3.1",
sectionChildren: [],
},
{
name: "section 3.1.2",
sectionParentName: "section 3.1",
sectionChildren: [
{
name: "section 3.1.2.1",
sectionParentName: "section 3.1.2",
sectionChildren: [],
},
{
name: "section 3.1.2.2",
sectionParentName: "section 3.1.2",
sectionChildren: [],
},
],
},
],
},
{
name: "section 3.2",
sectionParentName: "section 3",
sectionChildren: [],
},
],
},
];
const findParent = (MenuRoot, parentName) => {
const findSection = MenuRoot.find((section) => {
// if (section.name.match(parentName, "i")) {
if (section.name === parentName) {
const found = section.sectionChildren;
return found;
} else {
return findParent(section.sectionChildren, parentName);
}
});
return findSection;
};
console.log(findParent(MenuRoot, "section 3.1.2"));