JS树形结构,通过子节点,查找上级所有父节点

数据结构


 let data = [
        {
          "id": 1,
          "label": "猫爷爷",
          "children": [
            {
              "id": 2,
              "label": "猫爸1",
              "children": [
                {
                  "id": 3,
                  "label": "猫崽1-1",
                },
                {
                  "id": 4,
                  "label": "猫崽1-2",
                }
              ],
            },
            {
              "id": 5,
              "label": "猫爸2",
              "children": [
                {
                  "id": 6,        //根据这个id,查找它的所有上级
                  "label": "猫崽2-1", 
                },
                {
                  "id": 7, 
                  "label": "猫崽2-2", 
                },
              ],
            },
          ]
        },
        {
          "id": 7,
          "label": "猪爷爷",
          "children": [
            {
              "id": 8,
              "label": "猪爸1",
              "children": [
                {
                  "id": 9,
                  "label": "猪崽1",
                },
                {
                  "id": 10,
                  "label": "猪崽2",
                }
              ],
            },
          ]
        },
      ]
      let target = { "id": 6, "label": "猫崽2-1" }
      let result = []
      this.findParent(data, target, result)  
      console.log(result) // 打印出结果:['猫爷爷', '猫爸2', '猫崽2-1']

实现方法

//data:要遍历的数据, target:查找目标, result用于装查找结果的数组
findParent(data, target, result) {
      for (let i in data) {
        let item = data[i]
        if (item.id === target.id) {
          //将查找到的目标数据加入结果数组中
          //可根据需求unshift(item.id)或unshift(item)
          result.unshift(item.label)
          return true
        }
        if (item.children && item.children.length > 0) {
          let ok = this.findParent(item.children, target, result)
          if (ok) {
            result.unshift(item.label)
            return true
          }
        }
      }
      //走到这说明没找到目标
      return false
    }

猜你喜欢

转载自blog.csdn.net/weixin_72589507/article/details/127898293