1 回答

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);
添加回答
舉報