亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用鍵“減少”嵌套數組到對象的最快方法+按鍵查找的最快方法

用鍵“減少”嵌套數組到對象的最快方法+按鍵查找的最快方法

慕婉清6462132 2021-11-25 16:51:28
我需要轉換這種類型的嵌套數組,以便能夠以最快的方式通過鍵 (id) 進行搜索:[   {      "id":1,      "name":"example1",      "items":[         {            "id":1,            "name":"example1",            "example":123         },         {            "id":2,            "name":"example1",            "example":123         }      ]   },   {      "id":2,      "name":"example1",      "items":[         {            "id":3,            "name":"example1",            "example":123         },         {            "id":4,            "name":"example1",            "example":123         }      ]   }]實際上有更多的嵌套數組(大約 4 個級別)。我目前的方法是做reduce每個級別然后我可以使用例如list[1].items[1].name. 這對我來說看起來非常緩慢和低效。我還在stackoverflow 上發現我可以創建查找表,id->index但這看起來具有相同的復雜性并且占用更多內存。有人有更好的主意來進行這種轉變嗎?我正在處理龐大的數據集,我開始覺得我需要找到更好的方法來處理數據。我這樣做是因為我需要在這個數據集中按 ID 快速搜索。在數組中搜索findIndex很慢。并且轉換需要處理,如上所述。我需要找到總體復雜度最低的選項。
查看完整描述

1 回答

?
MYYA

TA貢獻1868條經驗 獲得超4個贊

去轉型。這是一項值得付出代價的努力,因為您所做的每一次搜索都會從這項投資中受益。


這是一個轉換為Map用于檢索關聯對象的基于查找表的過程。它將以逗號分隔的 id 值字符串作為查找鍵:


function makeLookup(list, map=new Map, prefix="") {

    for (let obj of list) {

        map.set(prefix + obj.id, obj);

        if (obj.items) makeLookup(obj.items, map, prefix + obj.id + ",");

    }

    return map;

}



let list = [{ "id":1, "name":"example1", "items":[

     {"id":1, "name":"example2", "example":123},

     {"id":2, "name":"example3", "example":123}

  ]}, { "id":2, "name":"example4", "items":[

     { "id":3, "name":"example5", "example":123 },

     { "id":4, "name":"example6", "example":123 }

  ]}

];


// One-shot transformation

let lookup = makeLookup(list);


// Demo of a loookup

console.log(lookup.get("1,2").name);

console.log(lookup.get("2,3").example);


查看完整回答
反對 回復 2021-11-25
  • 1 回答
  • 0 關注
  • 218 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號