Javascript构建树层次结构 [英] Javascript building tree hierarchy
本文介绍了Javascript构建树层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var array = [{"grandpa","father"}, {"father"}, {"grandpa","father","me"}];
鉴于以上数组,我想生成如下所示的java脚本对象(JSON),有类似父子的结构。
Given the above array, I want to product a java-script object(JSON) like below, that has the parent-child like structure.
{"id":"grandpa",
"children":[
{"id":"father",
"children":[
{"id":"me",
"children":[]
}]
}]
}
推荐答案
如果您正在询问如何获取层次结构路径列表并创建树结构,请按以下步骤操作:
If you're asking how you would take a list of hierarchy paths and create a tree structure, here's how you could do it in JavaScript:
function convertToHierarchy(arry /* array of array of strings */)
{
var item, path;
// Discard duplicates and set up parent/child relationships
var children = {};
var hasParent = {};
for (var i = 0; i < arry.length; i++)
{
var path = arry[i];
var parent = null;
for (var j = 0; j < path.length; j++)
{
var item = path[j];
if (!children[item]) {
children[item] = {};
}
if (parent) {
children[parent][item] = true; /* dummy value */
hasParent[item] = true;
}
parent = item;
}
}
// Now build the hierarchy
var result = [];
for (item in children) {
if (!hasParent[item]) {
result.push(buildNodeRecursive(item, children));
}
}
return result;
}
function buildNodeRecursive(item, children)
{
var node = {id:item, children:[]};
for (var child in children[item]) {
node.children.push(buildNodeRecursive(child, children));
}
return node;
}
convertToHierarchy([["1","2"], ["1"], ["1","2","3"]]);
修改:
你的问题仍然含糊不清。我以前的版本假设了这两件事:
Your question is still ambiguous. My previous version assumed these two things:
- 每个节点ID唯一标识一个节点
- 指定的A层次结构路径可以从根节点以外的其他路径开始
在此示例中,我将假设以下内容:
In this sample, I'll assume the following:
- 节点ID不是唯一的,但它们在特定节点的 children 中是唯一的
- 所有层次结构路径都从树的根节点开始
- Node IDs are not unique, but they are unique within the children of a particular node
- All hierarchy paths start at the root node of the tree
以下是代码:
function convertToHierarchy(arry /* array of array of strings */)
{
// Build the node structure
var rootNode = {id:"root", children:{}}
for (var i = 0; i < arry.length; i++)
{
var path = arry[i];
buildNodeRecursive(rootNode, path, 0);
}
return rootNode;
}
function buildNodeRecursive(node, path, idx)
{
if (idx < path.length)
{
item = path[idx];
if (!node.children[item])
{
node.children[item] = {id:item, children:{}};
}
buildNodeRecursive(node.children[item], path, idx + 1);
}
}
返回层次结构,但格式有点不同。但是,你应该得到图片。
The hierarchy structure is returned, but the format's a bit different. However, you should get the picture.
这篇关于Javascript构建树层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文