从自引用数组转换为树中的嵌套数组 [英] Convert from self-reference array into nested array in tree
本文介绍了从自引用数组转换为树中的嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 angular-bootstrap-nav-tree
我从自引用表获得的数组就像这样:
I have Array that i get from self-reference table Like this:
var obj = [
{id:1,label:"Animal"},
{id:2,label:"Vigitable"},
{id:3,label:"Cats",parent:1},
{id:4,label:"black cat",parent:3},
{id:5,label:"orange",parent:2},
];
我想将其转换为嵌套如下:
I want to convert it to be nested like this:
var convrted = [
{id:1,label:"Animal",children[
{id:3,label:"Cats",parent:1,children[{id:4,label:"black cat",parent:3}]}
]},
{id:2,label:"Vigitable",children[
{id:5,label:"orange",parent:2}
]}
];
我希望它能无限制地动态工作。
I want it to work unlimited levels dynamic.
推荐答案
这将完成这项工作:
function nest (array) {
nested = [];
for (var i = 0; i < array.length; i++) {
var parent = array[i].parent;
if (!parent) {
nested.push(array[i]);
} else {
// You'll want to replace this with a more efficient search
for (var j = 0; j < array.length; j++) {
if (array[j].id === parent) {
array[j].children = array[j].children || [];
array[j].children.push(array[i]);
}
}
}
}
return nested;
}
的第二个循环是寻找父母的低效方式;如果您要嵌套多个项目,则需要将其替换为不扫描整个数组的内容。
The second for
loop is an inefficient way of finding the parent; if you ever have more than a few items to nest, you'll want to replace it with something that doesn't scan the entire array.
这篇关于从自引用数组转换为树中的嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文