编辑代码

/**
 * get object key path
 * @param ob
 * @param key
 * @param value
 * @returns {string}
 */
const findPath = (ob, key, value) => {
    const path = []

    const keyExists = (obj) => {
        if (obj === value) return true

        if (obj === undefined || (typeof obj !== 'object' && !Array.isArray(obj))) return false

        if (Object.prototype.hasOwnProperty.call(obj, key) && obj[key] === value) return true

        if (Array.isArray(obj)) {
            let parentKey = path.length ? path.pop() : ''
            for (let i = 0; i < obj.length; i++) {
                path.push(`${parentKey}[${i}]`)
                const result = keyExists(obj[i], key)
                if (result) return result
                path.pop()
            }
        } else {
            for (const k in obj) {
                if (Object.prototype.hasOwnProperty.call(obj, k)) {
                    path.push(k)
                    const result = keyExists(obj[k], key)
                    if (result) return result
                    path.pop()
                }
            }
        }
        return false
    }

    keyExists(ob)

    return path.join('.')
}


const obj = [
    {
        id: '0',
        children: [
            {
                id: '00',
                children: [
                    {
                        id: '000'
                    },
                    {
                        id: '001'
                    }
                ]
            },
            {
                id: '01',
                children: [
                    {
                        id: '010'
                    },
                    {
                        id: '011'
                    }
                ]
            }
        ]
    },
    {
        id: '1',
        children: [
            {
                id: '10',
                children: [
                    {
                        id: '100'
                    },
                    {
                        id: '101'
                    }
                ]
            }
        ]
    },
    {
        id: '2',
        children: [
            {
                id: '20',
                children: [
                    {
                        id: '200'
                    },
                    {
                        id: '201'
                    }
                ]
            },
            {
                id: '21',
                children: [
                    {
                        id: '210'
                    },
                    {
                        id: '211'
                    }
                ]
            }
        ]
    }
]

console.log(findPath(obj, 'id', '01'))