1. 程式人生 > 實用技巧 >JavaScript 樹狀陣列根據子節點查詢所有父節點

JavaScript 樹狀陣列根據子節點查詢所有父節點

function findParent(array, value, valueName = 'value', childrenName = 'children') {
    if (!value || !Array.isArray(array)) return []
    const result = []
    const seek = (array, value) => {
        let parentValue = ''
        const up = (array, value, lastValue) => {
            array.forEach(v => {
                const _v = v[valueName]
                const _c = v[childrenName]
                if (_v === value) return parentValue = lastValue
                if (_c && _c.length) up(_c, value, _v)
            })
        }
        up(array, value)
        if (parentValue) {
            result.unshift(parentValue)
            seek(array, parentValue)
        }
    }
    seek(array, value)
    return [...result, value]
}

Test

const array = [
    {
        value: 'A',
        children: [
            {
                value: '_A1',
                children: [
                    {
                        value: '__A1'
                    }
                ]
            },
            {
                value: '_A2'
            }
        ]
    },
    {
        value: 'B',
        children: [
            {
                value: '_B1'
            },
            {
                value: '_B2',
                children: [
                    {
                        value: '__B2',
                        children: [
                            {
                                value: '___B2',
                                children: [
                                    {
                                        value: '____B2'
                                    }
                                ]
                            }
                        ]
                    }
                ]
            },
            {
                value: '_B3',
                children: [
                    {
                        value: '__B3',
                        children: [
                            {
                                value: '___B3',
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

console.log(findParent(array, '___B2')) // => ["B", "_B2", "__B2", "___B2"]