js convert flat array to tree object All In One
js convert flat array to tree object All In One
const arr = [
{id: 1, name: '部门1', pid: 0},
{id: 2, name: '部门2', pid: 1},
{id: 3, name: '部门3', pid: 1},
{id: 4, name: '部门4', pid: 3},
{id: 5, name: '部门5', pid: 4},
];
const arrayToTree = (arr = [], key = 'pid') => {
let tree = {};
// 分组
const map = new Map();
for (const obj of arr) {
obj.children = [];
if(!map.has(obj[key])) {
map.set(obj[key], [obj]);
} else {
const temp = map.get(obj[key]);
map.set(obj[key], [...temp, obj]);
}
}
// for (const item of arr) {
// const id = item.id;
// const pid = item.pid;
// const temp = map.get(pid);
// if(!tree[id]) {
// tree[id] = {
// ...item,
// children: [],
// }
// } else {
// tree.children = [...temp];
// }
// }
console.log('map =', map);
console.log('map.size =', map.size);
for (const [key, value] of map) {
// console.log('key, value', key, value);
const temp = value[0];
const id = temp.id;
if(key === 0) {
tree = temp;
} else {
// 递归
tree.children = findChildren(map, id);
}
}
console.log('tree =', tree);
return [tree];
};
const findChildren = (map, id) => {
let result = [];
const arr = map.get(id) || [];
if(arr.length === 1 && arr[0].children.length === 0) {
result = arr;
} else {
// temp;
for (const obj of arr) {
obj.children = findChildren(map, obj.id);
result.push(obj);
}
}
return result;
};
arrayToTree(arr);
/*
map = Map {
0 => [ { id: 1, name: '部门1', pid: 0 } ],
1 => [ { id: 2, name: '部门2', pid: 1 }, { id: 3, name: '部门3', pid: 1 } ],
3 => [ { id: 4, name: '部门4', pid: 3 } ],
4 => [ { id: 5, name: '部门5', pid: 4 } ]
}
map.size = 4
*/
/*
const obj = {
1: 1,
b: 'b',
3: '3c',
};
for (const [key, value] of Object.entries(obj)) {
console.log('key, value', key, value);
}
const arr = [1, 'b', '3c']
for (const [index, value] of Object.entries(arr)) {
console.log('index, value', index, value);
}
// 二维数组
const map = new Map([[1, 1], ['b', 'b'], [3, '3c']]);
for (const item of map) {
console.log('item', item);
}
*/
refs
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/15755803.html
未经授权禁止转载,违者必究!