对比两个树结构数据,把b树的值赋值给a树

本文介绍了一种使用递归方法更新两组树形结构数据中节点显示状态的算法。首先通过递归遍历B树结构数组获取每个节点的ID和显示状态,并将这些信息存储到一个新数组C中。随后再次递归遍历A树结构数组,根据C数组中的信息更新对应节点的显示状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:先递归b数组,得到 c= [{id,show}]
再递归a数组,遍历c,id相同,修改a

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <script>
    var ATreeData = [ // A树结构数组
      {
        id: 1,
        text: 1,
        show: true,
        children: [
          {
            id: 1.1,
            text: 1.1,
            show: true
          }
        ],
      },
      {
        id: 2,
        text: 2,
        show: true
      }
    ]


    var BTreeData = [ // B树结构数组
      {
        id: 1,
        text: 1,
        show: false,
        children: [
          {
            id: 1.1,
            text: 1.1,
            show: false
          }
        ],
      },
      {
        id: 2,
        text: 2,
        show: false
      }
    ]

    var CData = [] // 用于保存[{id,show}]

    function diguiB(arr) {
      arr.forEach((item, index, arr) => {
        let obj = {
          id: item.id,
          show: item.show
        }
        CData.push(obj)
        if (item.children instanceof Array) { // 有children数组
          this.diguiB(item.children)
        }
      });
    }

    diguiB(BTreeData)

    console.log('CData')
    console.log(CData)

    // 递归数组a
    function diguiA(arr) {
      arr.forEach((item, index, arr) => {

        for (let i = 0; i < CData.length; i++) {
          if (item.id == CData[i].id) {
            item.show = CData[i].show
          }
        }

        if (item.children instanceof Array) { // 有children数组
          this.diguiA(item.children)
        }

      });
    }

    diguiA(ATreeData)

    console.log('ATreeData')
    console.log(ATreeData)

  </script>

</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值