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);
添加回答
举报