前端笔试题：数组转树形结构

``````var data = [
{ parentId: 0, id: 1, value: '1' },
{ parentId: 3, id: 2, value: '2' },
{ parentId: 0, id: 3, value: '3' },
{ parentId: 1, id: 4, value: '4' },
{ parentId: 1, id: 5, value: '5' }
]``````

``````[
{
id:1,
value:'1',
children:[
{id:4,value:'4',children:[]},
{id:5,value:'5',children:[]}
]
},{
id:3,
value:'3',
children:[
{id:2,value:'2',children:[]}
]
}
]
``````

``````function convertArrayToTree(arr){
let
idsMap = {},
result = [],
node,
parentNode,
item,
j,
leng = arr.length;
for(j = 0; j <= leng; j++ ){

item = arr[j];
if(!idsMap['\$'+ item.id]){
node = {id: item.id, children: []}
idsMap['\$'+ item.id] = node;
}else{
node = idsMap['\$'+ item.id];
}
node.value = item.value;

if(item.parentId === 0){
result.push(node);
}else{
if(!idsMap['\$'+ item.parentId]){
parentNode = {id: item.parentId, children: []}
idsMap['\$'+ item.parentId] = parentNode;
}else{
parentNode = idsMap['\$'+ item.parentId];

}
parentNode.children.push(node);
}
}
return result;
}

``````

1.1k 声望
14 粉丝