gpt4 book ai didi

javascript - 被选元素在哪些元素中?

转载 作者:行者123 更新时间:2023-11-29 15:07:37 25 4
gpt4 key购买 nike

我有一个数组。数组中的元素表示菜单元素。我想根据我选择的菜单项创建“面包屑”。但是,它在工作时会在 3 个深度后动态提供错误。

// My Array

const menuArray = [{
"label": "Dashboard"
},
{
"label": "Products",
"items": [{
"label": "All Products"
},
{
"label": "New Product"
},
{
"label": "Product Categories"
}
]
},
{
"label": "Posts",
"items": [{
"label": "All Posts"
},
{
"label": "New Post"
},
{
"label": "Post Categories"
}
]
},
{
"label": "Sliders"
},
{
"label": "Settings",
"items": [{
"label": "General Settings"
},
{
"label": "User",
"items": [{
"label": "Your Profile"
},
{
"label": "Edit Profile"
}
]
},
{
"label": "Social Settings"
},
{
"label": "Link Settings"
}
]
}
];

// The function I experiment with
writeParent(event, arr) {

let ct = 0;
let found = false;
let parentsLine = [];

arr.some((e) => {
parentsLine = [];
let curr = e;
for (curr; curr.items != null; curr = curr.items[0]) {
if (event.label == curr.label) {
found = true;
return true;
}
parentsLine.push(curr.label);

}

if (event.label == curr.label) {
found = true;
return true;
}


});
if (found) {
return parentsLine;
} else {
return 'ERR: elm not found';
}
}


console.log(writeParent({
"label": "Edit Profile"
}, menuArray));

比如我选择的元素是;

{
"label": "New Post"
}

我要得到;

[
{
"label": "Posts"
},
{
"label": "New Post"
}
]

或者

如果我选择的元素是;

{
"label": "Edit Profile"
}

我要得到;

[
{
"label": "Settings"
},
{
"label": "User"
},
{
"label": "Edit Profile"
}
]


我不知道如何找到所选元素的父元素。我该怎么做?

最佳答案

我已经解决了这个问题。

menuArray = [{
"label": "Dashboard"
},
{
"label": "Products",
"items": [{
"label": "All Products"
},
{
"label": "New Product"
},
{
"label": "Product Categories"
}
]
},
{
"label": "Posts",
"items": [{
"label": "All Posts"
},
{
"label": "New Post"
},
{
"label": "Post Categories"
}
]
},
{
"label": "Sliders"
},
{
"label": "Settings",
"items": [{
"label": "General Settings"
},
{
"label": "User",
"items": [{
"label": "Your Profile"
},
{
"label": "Edit Profile"
}
]
},
{
"label": "Social Settings"
},
{
"label": "Link Settings"
}
]
}
];

function find(array, event) {
if (typeof array != 'undefined') {
for (let i = 0; i < array.length; i++) {
if (array[i].label == event.label) return [event.label];
let a = this.find(array[i].items, event);
if (a != null) {
a.unshift(array[i].label);
return a;
}
}
}
return null;
}

console.log(find(menuArray, { "label": "Edit Profile" }));

关于javascript - 被选元素在哪些元素中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58400896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com