概述
将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"
}]
}]
}]
最后
以上就是忧郁棒棒糖为你收集整理的【Javascript】使用递归将嵌套对象数组转为树状嵌套结构的全部内容,希望文章能够帮你解决【Javascript】使用递归将嵌套对象数组转为树状嵌套结构所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复