我有一个ID数组和一个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或更低版本上不可用,但MDN可以使用polyfill。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句