关上收藏夹发现还有 18 年未实现的文章,
粗略看了下发现居然还能看懂,
目标是把一个树形构造拍平获取所有的节点。
获取树形构造的所有节点
let tree = {
"id": 1,
"label": "一级 1",
"children": [{
"id": 3,
"label": "二级 2-1",
"children": [{
"id": 4,
"label": "三级 3-1-1"
}, {
"id": 5,
"label": "三级 3-1-2",
"disabled": true
}]
}, {
"id": 2,
"label": "二级 2-2",
"disabled": true,
"children": [{
"id": 6,
"label": "三级 3-2-1"
}, {
"id": 7,
"label": "三级 3-2-2",
"disabled": true
}]
}]
}
/**
* 把树形构造拍平获取所有节点
* @method getNode
* @param {Object} node 要拍平构造的树对象
* @return {Array} 拍平后的节点数组,不蕴含节点的子节点信息
* @author 朱阳星
* @email zhuyangxing@foxmail.com
* @datetime 2018-04-01T16:42:52+080
*/
function getNode(node) {let result = []
let _getNode = function (node) {let tmp =JSON.parse(JSON.stringify(node))
delete tmp.children
result.push(tmp) // 移除拍平数组的子元素, 只保留节点相干元素
let child = node.children
if (child != undefined && child.length > 0) {
child.forEach(ele=>{arguments.callee(ele)
})
}
}
_getNode(node)
_getNode=null
return result
}
let result = getNode(tree)
console.log(result)
// 返回后果如下
[{ id: 1, label: '一级 1'},
{id: 3, label: '二级 2-1'},
{id: 4, label: '三级 3-1-1'},
{id: 5, label: '三级 3-1-2', disabled: true},
{id: 2, label: '二级 2-2', disabled: true},
{id: 6, label: '三级 3-2-1'},
{id: 7, label: '三级 3-2-2', disabled: true}
]