在数组和带有对象的数组上加下划线JS的区别 [英] Underscore JS difference on array and array with objects

查看:61
本文介绍了在数组和带有对象的数组上加下划线JS的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有某些数字的数组和一个具有某些对象的数组,如下所示:

I'm having an array with certain numbers and an array with certain objects, looking like this:

var names = [
  { id: 1, name: 'Alex'},
  { id: 2, name: 'John'},
  { id: 3, name: 'Mary'}
];

var blocked_ids = [1, 2];

现在,我想从名称数组中删除具有blocked_ids的对象.结果就是这样:

Now I would like to remove the objects with the blocked_ids from the names array. So the result would be this:

[
  { id: 3, name: 'Mary'}
]

您可以看到ID为1和2的对象不见​​了,因为数组"blocked_ids"包含了这些数字.如果它只有两个数组,我可以使用_.difference(),但是现在我必须将blocked_ids与数组对象内部的id进行比较.有人知道该怎么做吗?

As you can see the objects with id 1 and 2 are gone, because the array "blocked_ids" contained these numbers. If it where just two arrays, i could use _.difference(), but now I have to compare the blocked_ids with the id's inside the array's objects. Anyone knows how to do this?

推荐答案

您可以使用 _.reject 方法.

You could do this by using the _.reject method.

例如:

_.reject(names, function(name) {
    return blockedIds.indexOf(name.id) > -1;
});

请参见 JSFiddle .

这篇关于在数组和带有对象的数组上加下划线JS的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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