第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

通過key獲取深度嵌套對(duì)象的路徑

通過key獲取深度嵌套對(duì)象的路徑

慕桂英4014372 2023-09-14 17:58:47
我有一個(gè)深層嵌套的對(duì)象const myObject = {    a: {        b: {            c: [                {                    t: {finallyHere: 'no!'}                },                {                    d: {finallyHere: 'yes!'}                },            ]        }    }}我的輸出對(duì)象看起來像,output = [a, b, c, 1, d] 我將傳遞的函數(shù)是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];}我未定義,請幫助輸出
查看完整描述

1 回答

?
慕森卡

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個(gè)贊

您可以采用迭代和遞歸方法來檢查值是否是對(duì)象以及鍵是否存在。


如果不是,則迭代鍵并返回,如果函數(shù)的嵌套調(diào)用返回真值并立即返回。


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'));


查看完整回答
反對(duì) 回復(fù) 2023-09-14
  • 1 回答
  • 0 關(guān)注
  • 108 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)