【Javascript】使用递归将嵌套对象数组转为树状嵌套结构

该博客讲述了如何将ArcGIS Server上的图层信息转换成适用于Element UI Tree组件的数据结构。通过提供的FindObjectChildTree函数,实现了递归遍历并构建树形结构的过程,最终得到一个层次分明、包含所有子节点的Tree数据。
摘要由CSDN通过智能技术生成

将ArcGIS Server上的图层信息转为Element UI中的Tree控件数据结构:

let sample = [{
    "id": 0,
    "name": "00",
    "children": [1, 2]
  },
  {
    "id": 1,
    "name": "01",
    "children": [3, 4]
  },
  {
    "id": 2,
    "name": "02",
    "children": [5]
  },
  {
    "id": 3,
    "name": "03",
    "children": [6]
  },
  {
    "id": 4,
    "name": "04",
    "children": []
  },
  {
    "id": 5,
    "name": "05",
    "children": []
  },
  {
    "id": 6,
    "name": "06",
    "children": []
  }
]


// 返回一个节点的所有子节点

function FindObjectChildTree(objectArrayItem, originObjectArray, idPropName, namePropName, childPropName) {
  // 如果该子节点无子节点,即到达叶子节点,返回
  if (!objectArrayItem[childPropName] || objectArrayItem[childPropName].length == 0) {
    return {
      "childTree": {
        "id": objectArrayItem[idPropName],
        "name": objectArrayItem[namePropName]
      },
      "checkedID": [objectArrayItem[idPropName]]
    }
  }

  // 否则该节点含有子节点,需要对其子节点做递归
  // 注意使用let声明变量,将变量作用域限制在块级,实现闭包
  let childTree = {
    "id": objectArrayItem[idPropName],
    "name": objectArrayItem[namePropName],
    "children": []
  }

  let checkedID = []
  checkedID.push(objectArrayItem[idPropName])

  let childrenIDArray = objectArrayItem[childPropName];
  childrenIDArray.forEach(childID => {
    originObjectArray.forEach(originObject => {
      if (childID == originObject[idPropName]) {
        const findResult = FindObjectChildTree(originObject, originObjectArray, idPropName, namePropName, childPropName);
        childTree.children.push(findResult["childTree"]);
        checkedID.push(...findResult["checkedID"])
      }
    })
  });

  return {
    "childTree": childTree,
    "checkedID": checkedID
  };
}


let childTree = []
let checkID = []
sample.forEach(element => {
  id = element.id
  if (checkID.indexOf(id) == -1) {
    checkID.push(id)
    const findResult = FindObjectChildTree(element, sample, "id", "name", "children")
    childTree.push(findResult.childTree)
    checkID.push(...findResult.checkedID)
  }
});

console.log(JSON.stringify(childTree))


[{
  "id": 0,
  "name": "00",
  "children": [{
    "id": 1,
    "name": "01",
    "children": [{
      "id": 3,
      "name": "03",
      "children": [{
        "id": 6,
        "name": "06"
      }]
    }, {
      "id": 4,
      "name": "04"
    }]
  }, {
    "id": 2,
    "name": "02",
    "children": [{
      "id": 5,
      "name": "05"
    }]
  }]
}]

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值