Created
July 15, 2021 10:55
-
-
Save guxuerui/6f38557db922db706a60ead62ff9c7e8 to your computer and use it in GitHub Desktop.
将扁平数组转化为Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const arrayToTree = (items) => { | |
let results = []; | |
let map = {}; | |
items.forEach(el => { | |
let item = {...el, children: []}; | |
if (map[item.id]) { | |
item.children = map[item.id]; | |
} else { | |
map[item.id] = item.children; | |
} | |
if (item.pid) { | |
if (!map[item.pid]) { | |
map[item.pid] = []; | |
} | |
map[item.pid].push(item); | |
} else { | |
console.log('item: ', item); | |
results.push(item); | |
} | |
}); | |
map = null; | |
return results; | |
}; | |
let 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} | |
]; | |
console.log(arrayToTree(arr)); | |
// 时间复杂度 O(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment