js构建层级树的几种方法

 

const filterList = jiraList.filter(i => !i.parentKey ||

!jiraList.some(it => it.key === i.parentKey));

// 如果节点存在parentKey但是parentKey对应的对象不在数组内,则需要提升当前节点为父节点

const exceptParent = jiraList.filter(i => i.parentKey);

 

/**

js实现多层级树结构第一种方法

直接递归,不开辟新数组,算法复杂度较高,实现简单

*/

 

// 防止多次渲染数据不正确

jiraList.forEach(item => {

item.children = null;

});

 

const deepData = (item) => {

exceptParent.forEach(it => {

if (it.parentKey === item.key) {

item.children = item.children || [];

item.children.push(it);

deepData(it); // 对当前子节点进行递归

}

});

};

 

filterList.map(item => {

deepData(item); // 对顶层父节点进行递归

});


 

/**

js实现多层级树结构第二种方法

直接递归,开辟新数组

*/

const deepData = (item) => {

let arr = []; // 开辟新数组,防止多次渲染导致结果不正确

exceptParent.filter(it => it.parentKey === item.key)

.forEach(it => {

arr.push({

...it,

children: deepData(it)

});

});

return arr.length ? arr : null;

};

 

filterList.map(item => {

const children = deepData(item);

item.children = children;

});


 

/**

js实现多层级树结构第三种方法(第一种实现)

构建map对象,依靠指针引用构建树的父子关系

*/

const setTreeData = (arr) => {

// 删除所有 children,以防止多次调用

arr.forEach(item => {

item.children = null;

});

 

let map = {}; // 构建map

arr.forEach(i => {

map[i.key] = i; // 构建以key为键 当前数据为值

});

let treeData = [];

arr.forEach(child => {

// 如果能够在map对象中找到对应的对象,则当前的child不是父节点,需要push到父节点的children下

const mapItem = map[child.parentKey];

// 存在则表示当前数据不是最顶层数据

if (mapItem) {

// 这里找到的mapItem的指针指向的是arr,所以mapItem的改变会影响arr的改变

// 这里需要判断mapItem中是否存在children, 存在则插入push当前数据, 不存在则赋值children为[]然后再push当前数据

mapItem.children = mapItem.children || [];

mapItem.children.push(child);

// else对应的则是最顶层父节点数据

} else {

treeData.push(child);

}

});

return treeData;

};

console.log('seee', setTreeData(jiraList));


 

/**

js实现多层级树结构第三种方法(第二种实现)

构建map对象,依靠指针引用构建树的父子关系

想比如第三种方法的第一种实现,这里先把所有的顶级父节点取出来,然后针对子节点进行操作

*/

const setTreeData = (jiraList) => {

const exceptParent = jiraList.filter(i => i.parentKey);

// 删除所有 children,以防止多次调用

jiraList.forEach(item => {

item.children = null;

});

 

let map = {};

jiraList.forEach(i => {

map[i.key] = i;

});

exceptParent.forEach(child => {

const mapItem = map[child.parentKey];

mapItem.children = mapItem.children || [];

mapItem.children.push(child);

});

};

setTreeData(jiraList);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章