数据结构
let data = [
{
name: "1",
children: [{
name: "3"
}, {
name: "4"
}]
},
{
name: "2",
children: [{
name: "5"
}, {
name: "6",
children: [{name: "7"}]
}]
}
]
转成扁平化
function dataTree(data){
let result = [];
for (const item of data) {
result.push(item)
if (item.children === null || item.children === undefined) {
continue;
}
let getChildren = dataTree(item.children)
result = result.concat(getChildren)
}
return result
}
console.log("原数组结构",data);
console.log("扁平化的对象",dataTree(data));
运行结果
数据结构
let datas = [
{id: 1, name: 1, parentId: null},
{id: 2, name: 2, parentId: 1},
{id: 3, name: 3, parentId: 1},
{id: 4, name: 4, parentId: null},
{id: 5, name: 5, parentId: 4},
{id: 6, name: 6, parentId: 4},
{id: 7, name: 7, parentId: 6},
{id: 8, name: 8, parentId: 6},
]
转成树形结构
function dataList(data){
let map = {};
for(let item of data){
map[item.id] = item
}
let result = []; //存放数组
for(let item of data){
item.children = []; //给每个数组添加一个空children
if(item.parentId === null){
result.push(item)//最上级的标签
}else{
//相当于用这个 parentId 当做父Id去查找对比查找数据
let parent = map[item.parentId]
//添加到刚刚定义children数组中去
parent.children.push(item)
}
}
return result;
}
console.log("扁平化转换成树形结构:");
console.log("原数组结构",datas);
console.log("树形结构",dataList(datas));
运行结果
数据结构
const data = [
{
id: 1,
parentId: undefined,
name: 'TEST 1',
children: [
{
id: 5,
parentId:1,
name: 'TEST 5',
children: [
{
id: 10,
parentId:4,
name: 'TEST 10'
},
{
id: 11,
parentId:4,
name: 'TEST 11'
}
]
}
]
},
{
id: 2,
parentId: undefined,
name: 'TEST 2',
children: [
{
id: 6,
parentId:2,
name: 'TEST 6'
},
{
id: 7,
parentId:2,
name: 'TEST 7'
}
]
},
{
id: 3,
parentId: undefined,
name: 'TEST 3',
children: [
{
id: 8,
parentId:3,
name: 'TEST 8'
},
{
id: 9,
parentId:3,
name: 'TEST 9'
}
]
},
{
id: 4,
name: 'TEST 4',
children: [
]
}
]
根据parentId查找父节点
/**
*
* @param list 最外层传入的数组 也可以是 this.数组
* @param parentId 子节点对应的上级关系parentId
* @returns {*[]}
*/
function findP(list,parentId){
const result = []
/**
* 处理逻辑
* @param arr 要对比的数组
* @param parentId 传递进来数据要对比父id(相当于parentId)
*/
let forFn = function (arr,parentId){
for (let i = 0; i < arr.length; i++) {
let item = arr[i];
if (item.id === parentId){
result.push(item)
// console.log("递归数据",item)
// console.log("递归id",item.parentId)
forFn(list,item.parentId)
break
}else {
if (item.children){
forFn(item.children,parentId)
}
}
}
}
forFn(list,parentId);
return result;
}
console.log("数据结构==",data)
console.log("查询父类==",findP(data,11))
运行结果(会把自己及父节点保存下来)
需求:根据点击子节点查询没有就一直向上查
思路:拿到树形结构数组直接递归查询
难点:
1)获取懒加载的树形结构,(因为懒加载封装的数据结构是分开装的)
2)拼接成树形结构在处理
下面为实现例子 只列出大概实现思路
悲伤敌敌畏