javascript - 用键“减少”嵌套数组到对象的最快方法 + 用键查找的最快方法
问题描述
我需要转换这种类型的嵌套数组,以便能够以最快的方式通过键(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
很慢。如上所述,转换需要处理。
我需要找到总体复杂度最低的选项。
解决方案
去转型。这是一项值得付出的努力,因为每次搜索都会让您从这项投资中受益。
这是一个转换为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);
推荐阅读
- javascript - 在 Node 中使用 mySQL 导致 Async/Await 出现问题
- node.js - 如何使用节点从网站上抓取数据
- node.js - SyntaxError: Unexpected reserved word => prettier/third-party.js
- arrays - Dataweave:将正则表达式模式匹配到数组的每个元素
- vue.js - Vue-Router - 将数据从一个路由组件传递到另一个
- javascript - 为什么第二个 Javascript 函数返回 NaN?
- python - Itertools 加速美丽汤中的嵌套循环
- java - “load()”处的 cassandra-connector 问题
- r - ggplot:将具有给定宽度的边框添加到 geom_point()
- machine-learning - 如何学习使用 Vowpal Wabbit 的上下文强盗进行排名?