目的:把数组中元素关系是父子结构的 变成 树形结构。
思想以及步骤
- 把数组中 的元素 遍历到一个map中,id作为key
- 然后再循环该数组获取每一个元素,查找该元素的父节点,如果有父节点就加入到节点的子树中。没有父节点该节点就是根节点。(查找父节点的方式是 通过元素 pid 去 map中查找)。
具体的代码实现 注:代码中包含了一些ES6 的语法。
新建一个Collections.js 文件
// 集合 工具类
function required(item, message = '') {
if (!item) {
throw new Error(message + 'is required');
}
}
const Collections = {
/**
*
* @param sourceArray 要转换树形 结构的原数据
* @param rootNodeIdentifier 根节点标识符
* @param pIdentifier 父节点标识符
* @param cIdentifier 直接点标识符
* @return {Error|IterableIterator<any>} 正常情况下返回 树形结构的数组
*/
turnTree(sourceArray, rootNodeIdentifier, pIdentifier, cIdentifier) {
required(sourceArray, '要转换的数组不能为空');
required(pIdentifier, '父节点标识符不能为空');
required(cIdentifier, '当前节点标识符不能为空');
let sourceArrayCopy = [...sourceArray];
if (pIdentifier === cIdentifier) {
return new Error('当前节点标识符不能和父节点标识符相同');
}
// 遍历数组添加到map
let sourceMap = new Map();
sourceArrayCopy.forEach(item => {
item.children = null;
sourceMap.set(item[cIdentifier], item)
});
// 树形节点集合
let tree = new Map();
while (sourceArrayCopy.length > 0) {
sourceArrayCopy.forEach((item, index) => {
if (rootNodeIdentifier === item[pIdentifier]) {
tree.set(item[cIdentifier], item);
sourceArrayCopy.splice(index, 1)
}else {
const node = sourceMap.get(item[pIdentifier]);
if (node.children == null) {
node.children = [];
}
node.children.push(item);
sourceArrayCopy.splice(index, 1)
}
});
}
sourceMap = null;
sourceArrayCopy = null;
return [...tree.values()];
}
};
export default Collections;
测试用例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="module">
import Collections from './Collections.js'
let array = [
{
pid: null,
id: 1,
name: '蓝色小区',
},
{
pid: 1,
id: 11,
name: 'A栋',
},
{
pid: 11,
id: 111,
name: '7楼',
},
{
pid: null,
id: 2,
name: '绿色小区',
},
{
pid: 2,
id: 20,
name: 'A栋',
},
{
pid: 20,
id: 200,
name: '20楼',
}
,
{
pid: 200,
id: 201,
name: '705房间',
}
];
let turnTree = Collections.turnTree(array,null,'pid','id');
console.log(array);
console.log(turnTree)
</script>
</body>
</html>
提示: 如果现在浏览器直接运行 import 指令 需要如下写法:
// type="module" 是关键
<script type="module">
import Collections from './Collections.js'
版权声明:本文为qq_36537108原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。