1.遍历树的层级关系1)先整理数据2)找到id和数据的映射关系3)然后找到父节点的数据,进行存储代码如下
test() {

const list = [

{ id: "123", parentId: "", children: [] },

{ id: "124", parentId: "123", children: [] },

{ id: "125", parentId: "124", children: [] },

{ id: "126", parentId: "125", children: [] },

{ id: "127", parentId: "126", children: [] }

];

const mapList = [];

const tree = [];

list.forEach(item => {



mapList[item.id] = item;

});

list.forEach(item => {

const parentNode = mapList[item.parentId];

if (!parentNode) {


if (!item.children) {

item.children = []

}


tree.push(item);

} else {


if (!parentNode.children) {

parentNode.children = []

}


parentNode.children.push(item);

}

});

console.log("tree", tree);

},
test() {

const list = [

{ id: "123", parentId: "", children: [] },

{ id: "124", parentId: "123", children: [] },

{ id: "125", parentId: "124", children: [] },

{ id: "126", parentId: "125", children: [] },

{ id: "127", parentId: "126", children: [] }

];

const mapList = [];

const tree = [];

list.forEach(item => {



mapList[item.id] = item;

});

list.forEach(item => {

const parentNode = mapList[item.parentId];

if (!parentNode) {


if (!item.children) {

item.children = []

}


tree.push(item);

} else {


if (!parentNode.children) {

parentNode.children = []

}


parentNode.children.push(item);

}

});

console.log("tree", tree);

},以上就是本文的全部内容,希望对大家的学习有所帮助。