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];
Now I would like to remove the objects with the blocked_ids from the names array. So the result would be this:
现在我想从names数组中删除带有blocked_ids的对象。结果就是:
[
{ id: 3, name: 'Mary'}
]
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?
如您所见,id为1和2的对象消失了,因为数组“blocked_ids”包含这些数字。如果只有两个数组,我可以使用_.difference(),但现在我必须将blocked_ids与数组对象中的id进行比较。谁知道怎么做?
3 个解决方案
#1
#2
1
Assuming block-ids
you have given is an array of Ids, You can use reject
like bellow
假设你给出的block-id是一个Ids数组,你可以使用像bellow一样的拒绝
var arr = [ { id: 1,
name: 'Alex'},
{ id: 2,
name: 'John'},
{ id: 3,
name: 'Mary'}
];
var block_ids = [1,2];
var result = _.reject(arr, function (obj) {
return block_ids.indexOf(obj.id) > -1;
});
console.log(result);
DEMO
#3
0
Pure ECMAScript solution:
纯ECMAScript解决方案:
names.filter(function(element) {
return blocked_ids.indexOf(element.id) === -1}
);
#1
0
You could do this by using the _.reject
method.
您可以使用_.reject方法执行此操作。
For example:
例如:
_.reject(names, function(name) {
return blockedIds.indexOf(name.id) > -1;
});
See this JSFiddle.
看到这个JSFiddle。
#2
1
Assuming block-ids
you have given is an array of Ids, You can use reject
like bellow
假设你给出的block-id是一个Ids数组,你可以使用像bellow一样的拒绝
var arr = [ { id: 1,
name: 'Alex'},
{ id: 2,
name: 'John'},
{ id: 3,
name: 'Mary'}
];
var block_ids = [1,2];
var result = _.reject(arr, function (obj) {
return block_ids.indexOf(obj.id) > -1;
});
console.log(result);
DEMO
#3
0
Pure ECMAScript solution:
纯ECMAScript解决方案:
names.filter(function(element) {
return blocked_ids.indexOf(element.id) === -1}
);