var list =[
{
name: '贵州',
id: '01',
parent: 0
},
{
name: '白云',
id: '010101',
parent: '0101'
},
{
name: '遵义',
id: '0102',
parent: '01'
},
{
name: '贵阳',
id: '0101',
parent: '01'
},
];
var result = getTrees(list, 0);
function getTrees(list, parentId) {
let items = {};
// 获取每个节点的直属子节点,*记住是直属,不是所有子节点
for (let i = 0; i < list.length; i++) {
let key = list[i].parent;
if (items[key]) {
items[key].push(list[i]);
} else {
items[key] = [];
items[key].push(list[i]);
}
}
return formatTree(items, parentId);
}
function formatTree(items, parentId) {
let result = [];
if (!items[parentId]) {
return result;
}
for (let t of items[parentId]) {
t.children = formatTree(items, t.id)
result.push(t);
if (!t.children.length) {
delete t.children;
}
}
return result;
}
console.log(result);
var list =[
{
name: '贵州',
id: '01',
parent: 0
},
{
name: '白云',
id: '010101',
parent: '0101'
},
{
name: '遵义',
id: '0102',
parent: '01'
},
{
name: '贵阳',
id: '0101',
parent: '01'
},
];
function tree(list) {
var map = {};
list.forEach((v, i) => {
map[v.id] = v;
});
var result = [];
list.forEach(function (v, i) {
var parent = map[v.parent];
if(parent) {
(parent.children || (parent.children = [])).push(v);
} else {
result.push(v);
}
});
return result;
}
网友评论