通过key获取深度嵌套对象的路径

我有一个深层嵌套的对象


const myObject = {

    a: {

        b: {

            c: [

                {

                    t: {finallyHere: 'no!'}

                },

                {

                    d: {finallyHere: 'yes!'}

                },

            ]

        }

    }

}

我的输出对象看起来像,output = [a, b, c, 1, d] 我将传递的函数是getPath(myObject, 'd')


到目前为止我正在尝试的功能,


function getPath(obj, key) {

    paths = []


    function getPaths(obj, path) {

        if (obj instanceof Object && !(obj instanceof Array)) {

            for (var k in obj){

                paths.push(path + "." + k)

                getPaths(obj[k], path + "." + k)

            }

        }

    }


    getPaths(obj, "")

    return paths.map(function(p) {

        return p.slice(p.lastIndexOf(".") + 1) == key ? p.slice(1) : ''

    }).sort(function(a, b) {return b.split(".").length - a.split(".").length;})[0];

}

我未定义,请帮助输出


慕桂英4014372
浏览 85回答 1
1回答

慕森卡

您可以采用迭代和递归方法来检查值是否是对象以及键是否存在。如果不是,则迭代键并返回,如果函数的嵌套调用返回真值并立即返回。const    getPath = (o, target) => {        if (!o || typeof o !== 'object') return;        if (target in o) return [target];        for (const k in o) {            const temp = getPath(o[k], target);            if (temp) return [k, ...temp];        }    };    object = { a: { b: { c: [{ t: { finallyHere: 'no!' } }, { d: { finallyHere: 'yes!' } } ] } } };    console.log(getPath(object, 'd'));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript