直接上代码吧,里面有相应注释,框架用的是React,基本不影响看里面函数的代码,代码底部render里是函数调用,欢迎留言交流。
import React, { Fragment } from 'react';
class Demo5 extends React.PureComponent{
constructor(props) {
super(props);
this.state={
arrayData : [
{
id: 1, val: '学校', parentId: 0 // 也可能为null,则需进行相应处理
}, {
id: 2, val: '班级1', parentId: 1
}, {
id: 3, val: '班级2', parentId: 1
}, {
id: 4, val: '学生1', parentId: 2
}, {
id: 5, val: '学生2', parentId: 2
}, {
id: 6, val: '学生3', parentId: 3
},
],
treeData:[
{
id: 1,
val: '学校',
children: [{
id: 2,
val: '班级1',
children: [
{
id: 4,
val: '学生1',
children: []
},
{
id: 5,
val: '学生2',
children: []
}
]
}, {
id: 3,
val: '班级2',
children: [{
id: 6,
val: '学生3',
children: []
}]
}]
}
]
}
}
componentDidMount() {
}
// 数组转树
handleConvertA = () => {
const { arrayData } = this.state;
// let temp = arrayData.shift(); // 若第一个的父节点不为0时,先将第一个父节点处理一下,再调用递归
// let tree = {
// id:temp.id,
// val:temp.val,
// }
let TreeData = this.arrayToTree(arrayData,0);
// if(TreeData.length > 0){
// tree.children = TreeData;
// }
console.log(TreeData);
}
arrayToTree = (data,parentId) => {
let result = [];
for(let i = 0; i < data.length; i++){
if(data[i].parentId === parentId){
let obj = {
id:data[i].id,
val:data[i].val
}
let children = [];
children = this.arrayToTree(data,data[i].id);
if(children.length > 0){ // 注意需求子节点为空时是否展示子节点
obj.children = children;
}
result.push(obj);
}
}
return result;
}
// 树转数组
handleConvertB = () => {
const { treeData } = this.state;
let result = [];
this.treeToArray(treeData,result,0);
console.log(result);
}
treeToArray = (data,result,pid) => {
data.forEach((item) => {
let temp = {id:item.id, val:item.val,parentId:pid};
result.push(temp);
if(item.children.length > 0){
let pid = temp.id;
this.treeToArray(item.children,result,pid);
}
})
}
// 树转数组
treeToArrayByQueue = () => {
const { treeData } = this.state;
let result = [];
let queue = [];
treeData[0].parentId = 0; // 由于const解构赋值是浅拷贝,这里添加了一个parentId改变了原数据,若不能改变原state里的数据的话,需要使用深拷贝
queue.push(treeData[0])
while(queue.length > 0){
let temp = queue.shift();
let obj = {id:temp.id,val:temp.val,parentId:temp.parentId};
result.push(obj);
let len = temp.children.length;
for(let i = 0; i < len; i++){
temp.children[i].parentId = temp.id; //
queue.push(temp.children[i]);
}
}
console.log(result);
}
render(){
this.handleConvertA();
this.handleConvertB();
this.treeToArrayByQueue();
console.log(this.state.treeData); // treeToArrayByQueue函数调用时,由于浅拷贝,添加属性时改变了this.state.treeData
return(
<div>数组转树,树转数组,以及树转数组层次遍历使用队列版</div>
)
}
}
export default Demo5;