JS-JSONツリーで子ノードの親パスを見つける方法

2505 ワード





    
    JS-   JSON               
    
        const data = [{
                id: 11,
                pid: 'a1',
                text: 11,
                children: [{
                        id: 21,
                        pid: 'b1',
                        text: 21,
                        children: [{
                                id: 31,
                                pid: 'c1',
                                text: 31,
                                children: [{
                                        id: 41,
                                        pid: 'd1',
                                        text: 41,
                                        children: []
                                    },
                                    {
                                        id: 42,
                                        pid: 'd2',
                                        text: 42,
                                        children: []
                                    }
                                ]
                            },
                            {
                                id: 32,
                                pid: 'c2',
                                text: 32,
                                children: []
                            }
                        ]
                    },
                    {
                        id: 22,
                        pid: 'b2',
                        text: 22,
                        children: []
                    }
                ]
            },
            {
                id: 12,
                pid: 'a2',
                text: 12,
                children: []
            }
        ]

        function findIndexArray(data, id, indexArray) {
            let arr = Array.from(indexArray)
            for (let i = 0, len = data.length; i < len; i++) {
                arr.push(data[i].pid)
                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
        }

        console.log(findIndexArray(data, 42, [])) // ["a1", "b1", "c1", "d2"]