如果你问,你会如何利用层次路径列表,并创建一个树形结构,这里是你如何能做到这一点在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"]]);
编辑:
你的问题仍然不明确。我以前的版本假设这两个东西:
- 每个节点ID唯一标识
- 一个指定的层级路径可以在除根节点
在此示例中其他启动节点,我假设以下内容:
- 节点ID不是唯一的,但他们是一个特定节点的孩子内唯一
点
- 所有层次的路径开始在树
这里的根节点的代码:返回
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);
}
}
的层次结构,但格式有点不同。但是,你应该得到的照片。
那么是什么问题? – 2010-02-18 03:09:41
根据数组生成javascript对象 – user275031 2010-02-18 03:12:14
该数组的语法无效。 – SLaks 2010-02-18 03:12:49