openks / learn-vue

自定义组件文档
https://openks.github.io/learn-vue
0 stars 0 forks source link

20180402_获取树形结构的所有节点 #98

Open openks opened 6 years ago

openks commented 6 years ago

获取树形结构的所有节点

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
}
getNode(tree)