【记录】递归遍历树并修改节点对象的key

🚀🚀

🌞:【递归遍历树】
🔫: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); // 得到最终的遍历过的树
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值