has the following recursive function, which cannot return the correct result:
const navItems = [
{
name: "name1",
label: "",
items: [
{
name: "name2",
label: "",
items: [
{
name: "name3",
label: "-0",
items: [
{
name: "name4",
label: "-0-0",
items: "",
},
{
name: "name5",
label: "-0-1",
items: "",
},
],
},
{
name: "name6",
label: "-1",
items: "",
},
],
},
{
name: "name7",
label: "",
items: [
{
name: "name8",
label: "1",
items: "",
},
{
name: "name9",
label: "2",
items: "",
},
],
},
{
name: "name10",
label: "",
items: [
{
name: "name11",
label: "1",
items: "",
},
{
name: "name12",
label: "2",
items: "",
},
],
},
],
},
];
const navName = "name12";
const getSelectedLabel = (navItems, navName) => {
let selectedLabel;
const findSelectedLabel = (items, name) => {
items.forEach((item) => {
if (item.name === name) {
selectedLabel = item.label;
} else if (item.items && Array.isArray(item.items)) {
findSelectedLabel(item.items, name);
}
});
};
findSelectedKey(navItems, navName);
return selectedLabel;
};
I want to find the corresponding undefined, value according to the name value through the recursive function, but the function returns undefined, first and then performs the assignment. How should I modify it?
and I originally wrote not to nest outer functions:
const findSelectedLabel = (items, name) => {
items.forEach((item) => {
if (item.name === name) {
return item.label;
} else if (item.items && Array.isArray(item.items)) {
findSelectedLabel(item.items, name);
}
});
};
findSelectedLabel(navItems, navName)
find it directly and return this value, but it is also wrong. Although the function comes to the word return, it does not terminate the whole function, and finally returns undefined.
. many people say that the running result is correct, because name4 happens to be in the first layer, so it would be wrong to use navName = name12,.
and the use of for loop is also wrong. After using the for loop, it only recurses the first layer, only recursively layer by layer, and does not enter the for loop.
Thank you, gods ~