[英]Javascript Arrange Array in Tree Structure
I have created category hierarchy following a tutorial here Model Tree Structure with An Array Of Ancestors . 我已经按照此处的带有先祖数组的模型树结构教程创建了类别层次结构 。 When I do query, I am getting result which is identical to the following array dump. 当我查询时,我得到的结果与以下数组转储相同。
[
{id:1,name:'A', ancestors:[]}
,{id:2,name:'AA',parent:1, ancestors:[1]}
,{id:4,name:'AAA',parent:2, ancestors:[1,2]}
,{id:5,name:'AAB',parent:2, ancestors:[1,2]}
,{id:3,name:'AB',parent:1, ancestors:[1]}
,{id:6,name:'ABA',parent:3, ancestors:[1,3]}
,{id:7,name:'ABB',parent:3, ancestors:[1,3]}
,{id:8,name:'B', ancestors:[]}
]
Please help me dynamically transforming the above array to as below: 请帮助我将上面的数组动态转换为如下形式:
[
{id:1, name:'A', ancestors: [], children : [
//children of A
{id:2, name:'AA', parent:1, ancestors:[1], children:[
//children of AA
{id:4, name:'AAA', parent:2, ancestors:[1,2], children:[]}
, {id:5, name:'AAB', parent:2, ancestors:[1,2], children:[]}
]}
, {id:3, name:'AB', parent:1, ancestors:[1], children:[
//children of AB
{id:6, name:'ABA', parent:3, ancestors:[1,3], children:[]}
, {id:7, name:'ABB', parent:3, ancestors:[1,3], children:[]}
]}
]}
,
{id:8, name:'B', ancestors:[]}
] ]
I have been able to yield the following result so far 到目前为止,我已经能够得出以下结果
[
{id:1,name:'A', ancestors:[], children:[2,3]}
,{id:2,name:'AA',parent:1, ancestors:[1], children:[4,5]}
,{id:4,name:'AAA',parent:2, ancestors:[1,2], children:[]}
,{id:5,name:'AAB',parent:2, ancestors:[1,2], chldren:[]}
,{id:3,name:'AB',parent:1, ancestors:[1], children:[6,7]}
,{id:6,name:'ABA',parent:3, ancestors:[1,3], children:[]}
,{id:7,name:'ABB',parent:3, ancestors:[1,3], children:[]}
,{id:8,name:'B', ancestors:[], children:[]}
]
By writing this code : 通过编写以下代码:
//var items = _GIVEN AT THE TOP_;
var indexedItem = items.map(function(item){
return item.id;
});
items.forEach(function(item){
if(!item.parent) {return;}
var parent = items[indexedItem.indexOf(item.parent)];
if(!parent.children){parent.children = [];}
parent.children.push(item.id);
});
Here is my solution using recursion: 这是我使用递归的解决方案:
function findChildren(array, itemId){
var newItems = []
array.forEach(function(el,index){
if(el.parent == itemId)
{
var itemsClone = JSON.parse(JSON.stringify(items));
itemsClone.pop(index);
el.children = findChildren(itemsClone, el.id);
newItems.push(el);
}
});
return newItems;
}
var tree = findChildren(items);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.