Last active
December 4, 2018 11:58
-
-
Save BryanYang/b46194e4676a6eb22cb4ea3c1ab5183c to your computer and use it in GitHub Desktop.
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
/** | |
* 把平铺的 array 转成 树 | |
* | |
* 比如原始数列: | |
* [ | |
* {id: "13300", parentId: "13300", name: "蔬菜", status: 1}, | |
* {id: "13301", parentId: "13301", name: "饮料", status: 1}, | |
* {id: "13413", parentId: "13413", name: "青菜类", status: 1}, | |
* {id: "13696", parentId: "13696", name: "肉类", status: 1}, | |
* {id: "13700", parentId: "13696", name: "鱼肉", status: 1}, | |
* {id: "13701", parentId: "13700", name: "黑鱼肉", status: 1} | |
* ] | |
* | |
* 转变成: | |
* [ | |
* {id: "13300", parentId: "13300", name: "蔬菜", status: 1}, | |
* ... | |
* {id: "13696", parentId: "13696", name: "肉类", status: 1, list: [ | |
* {id: "13700", parentId: "13696", name: "鱼肉", status: 1, list: [ | |
* {id: "13701", parentId: "13700", name: "黑鱼肉", status: 1} | |
* ]}, | |
* ]}, | |
* ] | |
*/ | |
interface TreeNode { | |
id: string; | |
list?: TreeNode[]; | |
// tslint:disable-next-line:no-any | |
[key: string]: any; | |
} | |
interface OriginArray { | |
id: string; | |
parentId?: string; | |
// tslint:disable-next-line:no-any | |
[key: string]: any; | |
} | |
interface Array2Tree { | |
(param: Array<OriginArray>): TreeNode[]; | |
} | |
// 方法1 | |
const traver = (nodes: TreeNode[], array: OriginArray[]) => { | |
const nextNodes: TreeNode[] = []; | |
const others: OriginArray[] = []; | |
let i = 0, | |
j = 0; | |
while (i < array.length) { | |
while (j < nodes.length) { | |
if (array[i].parentId === nodes[j].id) { | |
nodes[j].list = nodes[j].list || []; | |
nodes[j].list!.push(array[i]); | |
nextNodes.push(array[i]); | |
i++; | |
j=0; | |
break; | |
} else { | |
j++; | |
} | |
} | |
if (j === nodes.length) { | |
others.push(array[i]); | |
i++; | |
j=0; | |
} | |
} | |
others.length && nextNodes.length && traver(nextNodes, others); | |
}; | |
// 方法2 | |
const fn2: Array = (categories) => { | |
let result: any = []; | |
categories.forEach(item => { | |
if (item.parentId === item.id) { | |
result.push(item); | |
} else { | |
const parent = categories.find(it => it.id === item.parentId); | |
parent.list ? parent.list.push(item) : parent.list = [item]; | |
} | |
}); | |
return result; | |
} | |
const myFun: Array2Tree = array => { | |
const rootNodeArray = array.filter(a => a.id === a.parentId); | |
const others = array.filter(a => a.id !== a.parentId); | |
traver(rootNodeArray, others); | |
return rootNodeArray; | |
}; | |
export default myFun; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment