比较对象数组和ID数组 [英] Compare array of objects to array of ids

查看:168
本文介绍了比较对象数组和ID数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆