使用递归获取嵌套对象中的所有父级

Ayo*_*b k 5 javascript recursion object

我有以下对象

const object = {
    id: "1",
    name: "a",
    children: [
        {
            id: "2",
            name: "b",
            children: [
                {
                    id: "3",
                    name: "c"
                }
            ]
        },
        {
            id: "4",
            name: "d"
        }
    ]
};
Run Code Online (Sandbox Code Playgroud)

我需要一个接受对象和最后一个孩子的 id 并返回路径的函数,例如,以下调用:getPath(object, '3');应返回[{id: 1}, {id: 2}, {id: 3}]

我创建了该函数,但我只能访问第一个父级。

function getPath(model, id, parent) {
    if (model == null) {
        return;
    }
    if (model.id === id) {
        console.log(model.id, parent.id)
    }
    if (model.children) {
        model.children.forEach(child => getPath(child, id, model));
    }
}
Run Code Online (Sandbox Code Playgroud)

PS:物体的深度未知。

Nin*_*olz 6

您可以使用短路来迭代子级,并将函数与目标对象的路径移交。

function getPath(model, id) {
    var path,
        item = { id: model.id };

    if (!model || typeof model !== 'object') return;

    if (model.id === id) return [item];    
    
    (model.children || []).some(child => path = getPath(child, id));
    return path && [item, ...path];
    
}
const object = { id: "1", name: "a", children: [{ id: "2", name: "b", children: [{ id: "3", name: "c" }] }, { id: "4", name: "d" }] };

console.log(getPath(object, '42')); // undefined
console.log(getPath(object, '3'));  // [{ id: 1 }, { id: 2 }, { id: 3 }]
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)


Nic*_*ick 5

这非常接近。path考虑在递归函数中传递整个数组。以下是实现此目的的稍加修改的版本。

function getPath(model, id, path) {
    if (!path) {
      path = [];
    }

    if (model == null) {
        return;
    }
    if (model.id === id) {
        console.log(model.id, path)
    }
    if (model.children) {
        model.children.forEach(child => getPath(child, id, [...path, model.id]));
    }
}

const object = {
    id: "1",
    name: "a",
    children: [
        {
            id: "2",
            name: "b",
            children: [
                {
                    id: "3",
                    name: "c"
                }
            ]
        },
        {
            id: "4",
            name: "d"
        }
    ]
};

getPath(object, "3");
Run Code Online (Sandbox Code Playgroud)