列表数据转树形数据
文章目录
let listToTree = (list, id = 'id', pId = 'pId') => {
let map = {},
listMap = {},
rootList = [];
for (let i = 0, max = list.length; i < max; i++) {
let one = Object.assign({}, list[i]);
map[one[id]] = one;
if (listMap[one[id]]) {
one.children = listMap[one[id]];
}
if (one.hasOwnProperty(pId) && one[pId] !== '') {
if (map[one[pId]]) {
let c = map[one[pId]].children || (map[one[pId]].children = []);
c.push(one);
} else {
if (!listMap[one[pId]]) listMap[one[pId]] = [one];
else listMap[one[pId]].push(one);
}
} else {
rootList.push(one);
}
}
return { list: rootList, map };
};
使用
let data=[{
id:1,
text:'1'
},{
id:2,
pId:1,
text:'2'
}];
let tree=listToTree(data);
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论