SOURCE

function getTreeData(depth = 4, length = 10) {
    const data = {
        name: 'root',
        children: []
    }

    for (let i = 1; i <= length; i++) {
        const child = getLevelData(`tree-${i}-1`)
        
        let count = depth-1
        let currChild = child.children
        while(count) {
            currChild.push(getLevelData(`tree-${i}-${depth-count+1}`))
            currChild = currChild[0].children
            count--
        }

        data.children.push(child)
    }

    return data
}

function getLevelData(name) {
    return {
        name,
        children: [],
    }
}

function getParent(childName, treeData) {
    if (treeData.children.some(child => child.name === childName)) {
        return treeData
    }

    for (let i= 0; i < treeData.children.length; i++) {
        const parent = getParent(childName, treeData.children[i])
        if (parent) return parent
    }
}

function traverse(treeData) {
    console.log(treeData.name)
    if (treeData.children.length) {
        treeData.children.forEach(child => traverse(child))
    }
}

try {
    const treeData = getTreeData(10, 100)
    const parent = getParent('tree-98-8', treeData)
    console.log('parent: ', parent)
} catch(err) {
    console.error('err: ', err)
}
console 命令行工具 X clear

                    
>
console