javascript : 找到一个树型数据的一个节点及其所有父节点

如题。

(function () {
    let tree = {
        "id": 0,
        "label": "all",
        "children": [
            {
                "children": [
                    {
                        "children": [
                            {
                                "id": 210,
                                "label": "dashboard_panel"
                            },
                            {
                                "children": [
                                    {
                                        "id": 212,
                                        "label": "dashboard_card-edit"
                                    },
                                    {
                                        "id": 213,
                                        "label": "dashboard_card-view"
                                    }
                                ],
                                "id": 211,
                                "label": "dashboard_card"
                            }
                        ],
                        "id": 209,
                        "label": "dashboards"
                    }
                ],
                "id": 208,
                "label": "dashboard_manage"
            },
            {
                "id": 300,
                "label": "user_manage",
                "children": [
                    {
                        "id": 312,
                        "label": "user_card-edit"
                    },
                    {
                        "id": 313,
                        "label": "user_card-view"
                    }
                ]
            }
        ]
    };


    let ids = [213, 312, 211]
    for (let id of ids) {
        let arr = findIndexArray(tree.children, id, []);
        console.log(arr);
    }

})()


function findIndexArray(data, id, indexArray) {
    let arr = Array.from(indexArray)
    for (let i = 0, len = data.length; i < len; i++) {
        arr.push({ id: data[i].id, label: data[i].label })
        if (data[i].id === id) {
            return arr
        }
        let children = data[i].children
        if (children && children.length) {
            let result = findIndexArray(children, id, arr)
            if (result) return result
        }
        arr.pop()
    }
    return false
}

 

posted on 2020-04-28 20:49  fox_charon  阅读(983)  评论(0编辑  收藏  举报

导航