比较对象数组和ID数组 [英] Compare array of objects to array of ids
问题描述
使用jQuery,我想使用ID数组来查找allObjects
数组中具有匹配的Id
值的对象.
Using jQuery, I would like to use an array of ids to find the objects inside the allObjects
array that have the matching Id
value.
var arrayOfIds = [1, 4, 5];
var allObjects = [{"Id":"1", "name":"aa"},{"Id":"2", "name":"bb"} ,{"Id":"3", "name":"cc"} ,{"Id":"4", "name":"dd"}, {"Id":"5", "name":"ee"}, {"Id":"6", "name":"ff"}, {"Id":"7", "name":"gg"}, {"Id":"8", "name":"hh"}, {"Id":"9", "name":"ii"}];
结果等于:
[{"Id":"1", "name":"aa"}, {"Id":"4", "name":"dd"}, {"Id":"5", "name":"ee"}]
到目前为止,我只能使用以下内容提取单个对象:
So far, I can only use the following to extract an individual object:
var result = $.grep(arrayOfIds, function(e) { return e.Id == 3; });
我觉得答案可能是通过对上述$ .grep查询进行某种修改而无法解决的.
I feel as though the answer might be achieved by amending the above $.grep query somehow but can't figure it out.
推荐答案
您不需要jQuery.您可以使用 Array.prototype.filter()
来过滤allObjects
和 Array.prototype.includes()
检查对象Id
属性是否在arrayOfIds
中:
You don't need jQuery for this. You can use Array.prototype.filter()
to filter allObjects
and Array.prototype.includes()
to check if the objects Id
property is in arrayOfIds
:
allObjects.filter(x=> arrayOfIds.includes(Number(x.Id)))
请参见关于JS Bin的演示.
这篇关于比较对象数组和ID数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!