我正在将移动导航中的用户导航“状态”作为数组获取。例如:
['3124', '5312', '5232']
我需要使用该状态来获取 ID 为“5232”的对象,位于该对象的下 3 层。
数组长度可以不同,这意味着它可以返回 1 到 5 个 id,因此我不必总是一直向下循环。
这就是导航数据的样子,使用与上面示例中使用的相同的 ID,我希望我的函数返回 ID 为“evening”的对象 '5232'
:
[
{
id: "3124",
name: "women",
children: [
{
id: "5312",
name: "dresses",
children: [
{
id: "8399",
name: "wedding",
children: []
},
{
id: "5232",
name: "evening",
children: []
}
]
},
{
id: "3291",
name: "shoes",
children: []
}
]
},
{
id: "9482",
name: "men",
children: [
{
id: "8292",
name: "jackets",
children: []
},
{
id: "3829",
name: "hats",
children: []
}
]
}
]
我一直在与几位同事讨论这个问题,但我们确实找不到有效地完成此操作的好方法。我们无法更改数据,但我们可以更改用户状态的保存方式(如果这是错误的)。
我真的可以使用一些意见和想法来如何以良好的方式解决这个问题。
最佳答案
在树中按路径查找节点的简单函数
function findNodeByPath(nodes, path) {
let node;
if (!path) return;
for (let id of path) {
if (!nodes) break;
for (let child of nodes) {
if (child.id === id) {
node = child;
nodes = node.children;
break;
}
}
}
return node;
}
let nodes = [
{
id: "3124",
name: "women",
children: [
{
id: "5312",
name: "dresses",
children: [
{
id: "8399",
name: "wedding",
children: []
},
{
id: "5232",
name: "evening",
children: []
}
]
},
{
id: "3291",
name: "shoes",
children: []
}
]
},
{
id: "9482",
name: "men",
children: [
{
id: "8292",
name: "jackets",
children: []
},
{
id: "3829",
name: "hats",
children: []
}
]
}
];
console.log(findNodeByPath(nodes, ['3124', '5312', '5232']));
关于javascript - 基于 ids 数组有效循环对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48210156/