gpt4 book ai didi

javascript - 如何遍历嵌套数组?

转载 作者:行者123 更新时间:2023-11-29 23:46:01 24 4
gpt4 key购买 nike

我试图通过从根节点遍历到叶节点来为每个节点保存路径。

例如,我在层次结构中有这样的节点:

Node - 1
Node-1-1
Node-1-1-1

每个节点的预期输出:

So for Node - 1 I would like to have value in property path : /myPath/Node - 1
So for Node-1-1 I would like to have value in property path : /myPath/Node - 1/Node-1-1
So for Node-1-1-1 I would like to have value in property path : /myPath/Node - 1/Node-1-1/Node-1-1-1

但是我得到的路径如下所示,我的 Node-1-1-1 代码:

"/myPath/Node-1-1-1"

但预期结果如下:

/myPath/Node - 1/Node-1-1/Node-1-1-1  (becuase Node-1-1-1 belongs to Node-1-1 but Node-1-1 in turn belongs to Node - 1).

演示:

var  tree =  JSON.parse('[{"name":"Node","nodes":[{"name":"Node-1","nodes":[{"name":"Node-1-1","nodes":[{"name":"Node-1-1-1","nodes":[],"path":null}],"path":null}],"path":null}],"path":null}]');

traverseTree(tree);
console.log(tree);
function traverseTree(nodes)
{
nodes.forEach(function (node) {
node.path= getPath(node.name)
if (node.nodes) {
traverseTree(node.nodes);
}
});
}

function getPath(name)
{
var path = "/myPath/";
path = path + name;
return path;
}

最佳答案

您可以收集路径中的所有节点,然后使用数组获取节点的完整路径。

var  tree =  JSON.parse('[{"name":"Node","nodes":[{"name":"Node-1","nodes":[{"name":"Node-1-1","nodes":[{"name":"Node-1-1-1","nodes":[],"path":null}],"path":null}],"path":null}],"path":null}]');

function traverseTree(nodes, path) {
path = path || [];
nodes.forEach(function (node) {
node.path = getPath(path.concat(node.name));
if (node.nodes) {
traverseTree(node.nodes, path.concat(node.name));
}
});
}

function getPath(name) {
var path = "/myPath/";
path = path + name.join('/');
return path;
}

traverseTree(tree);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

具有给定前缀的较短版本

var  tree =  JSON.parse('[{"name":"Node","nodes":[{"name":"Node-1","nodes":[{"name":"Node-1-1","nodes":[{"name":"Node-1-1-1","nodes":[],"path":null}],"path":null}],"path":null}],"path":null}]');

function traverseTree(nodes, path) {
path = path || [];
nodes.forEach(function (node) {
var p = path.concat(node.name);
node.path = p.join('/')
if (node.nodes) {
traverseTree(node.nodes, p);
}
});
}

traverseTree(tree, ['', 'myPath']);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何遍历嵌套数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44112792/

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