🚀🚀
🌞:【递归遍历树】
🔫:zZhiqg 的主页
🍉:递归遍历树状数据并修改 key 值
**递归遍历树
初识 递归遍历树
前段时间干活因为后端给的树状数据的 key 不是自己想要的,于是就想着怎么能够修改每个节点的 key
代码如下
// 示例数据
const options = [
{
nameNum: "1",
name: "小明",
childrenList: [
{
nameNum: "11",
name: "小明明",
childrenList: [
{
nameNum: "111",
name: "小明同学",
childrenList: null,
},
{
nameNum: "112",
name: "小明学弟",
childrenList: null,
},
],
},
],
},
{
nameNum: "2",
name: "小红",
childrenList: [
{
nameNum: "22",
name: "小红红",
childrenList: null,
},
],
},
];
/*
代码
*/
console.log("数据初始", options);
const data = options;
const mapTree = (org) => {
const haveChildren =
Array.isArray(org.childrenList) && org.childrenList.length > 0;
return {
label: org.name,
value: org.nameNum,
children: haveChildren ? org.childrenList.map((i) => mapTree(i)) : null,
};
};
let res = [];
res = data.map((org) => mapTree(org));
console.log("最终的数据", res); // 得到最终的遍历过的树