/**
* listToTree.js
*
* @param {*} list 将要变成树的列表
* @param {*} id 元素id字段名称
* @param {*} parentId 元素父id名称
* @return {*} tree
* 张志光 2021/6/23
*/
const listToTree = function(list, id, parentId) {
let tree = [];
tree = list.filter(
item1 =>
!list.find((item2, index) => {
// 如果有父节点
if (item1[parentId] === item2[id]) {
// 放进它父节点的children数组中;如果children不存在,初始化为空数组
list[index].children = list[index].children || [];
list[index].children.push(item1);
}
// find返回第一个符合条件的元素,找到后,剩余的元素不再判断
return item1[parentId] === item2[id];
})
);
return tree;
};
export default listToTree;