使用Jquery或JavaScript从对象数组中删除对象数组

时间:2022-09-25 07:53:48

Might be duplicate, but I couldn't find it. So I have two arrays of objects:

可能重复,但我找不到它。所以我有两个对象数组:

var a = [{id: '1', name: 'bob'}, {id: '2', name: 'bill'}]
$scope.b = [{id: '4', name: 'jack'}, {id: '2', name: 'bill'}, {id: '1', name: 'bob'}, {id: '3', name: 'john'}]

I want to remove all the a elements from b. I have tried:

我想从b中删除所有元素。我努力了:

$scope.b = $scope.b.filter(function(item){
   return a.indexOf(item) === -1;
});

unfortunately, for some reason, the index is always -1, so nothing gets deleted. with some console.log-s

遗憾的是,由于某种原因,索引始终为-1,因此不会删除任何内容。与一些console.log-s

console.log(item);
console.log(a);
console.log(a.indexOf(item));

, this is how the data looks like:

,这就是数据的样子:

Resource {id: 4, name: "jack"}
[Resource, Resource, Resource, Resource, $promise: Promise, $resolved: true]
-1

1 个解决方案

#1


2  

You can do it like this

你可以这样做

// get all id's from a
var a = [{id: '1', name: 'bob'}, {id: '2', name: 'bill'}].map(function (el) {
    return el.id;
});

// search item.id in array with id's
$scope.b = $scope.b.filter(function(item){
   return a.indexOf(item.id) === -1;
});

#1


2  

You can do it like this

你可以这样做

// get all id's from a
var a = [{id: '1', name: 'bob'}, {id: '2', name: 'bill'}].map(function (el) {
    return el.id;
});

// search item.id in array with id's
$scope.b = $scope.b.filter(function(item){
   return a.indexOf(item.id) === -1;
});