javascript - 基于 Node JS 中的其他数组过滤/搜索 JavaScript 对象数组

标签 javascript arrays node.js

我有一个 ids 数组和一个 JavaScript 对象数组。我需要使用 Node JS 中数组中的值来过滤/搜索 JavaScript 对象数组。

例如

var id = [1,2,3];

var fullData = [ 
    {id:1, name: "test1"}
   ,{id:2, name: "test2"}
   ,{id:3, name: "test3"}
   ,{id:4, name: "test4"}
   ,{id:5, name: "test5"}
];

使用上述数据,结果我需要:

var result = [ 
    {id:1, name: "test1"}
   ,{id:2, name: "test2"}
   ,{id:3, name: "test3"}
];

我知道我可以循环遍历两者并检查匹配的 id。但这是唯一的方法还是有更简单且资源友好的解决方案。

要比较的数据量约为 30-40k 行。

最佳答案

这可以解决问题,使用 Array.prototype.filter :

var result = fullData.filter(function(item){ // Filter fulldata on...
    return id.indexOf(item.id) !== -1; // Whether or not the current item's `id`
});                                    // is found in the `id` array.

请注意,此filter功能在IE 8或更低版本上不可用,但the MDN has a polyfill available .

关于javascript - 基于 Node JS 中的其他数组过滤/搜索 JavaScript 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25849178/

相关文章:

c - 读入数组直到文件末尾

python - 如何将浮点列表的 2d np.array 转换为浮点的 2d np.array,将列表值堆叠到行

node.js - Node 脚本抛出 uv_signal_start EINVAL

javascript - 如何下载文本文件并将其存储为 jQuery 中的字符串

javascript - js-hotkeys 在表单中的单词中间添加字母

javascript - JS : How to choose random pairs of items from an array

javascript - 如何根据另一个值 [JavaScript] 在对象数组中搜索特定值?

javascript - 没有 CoffeeScript 的 TowerJS?

javascript - 为 http-server 设置 MIME 类型

Javascript:如何从对象定义(如类)正确创建新的自定义实例