可能是重复的,但我找不到它。 所以我有两个对象数组:
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'}]
我想从 b 中删除所有 a 元素。 我试过:
$scope.b = $scope.b.filter(function(item){
return a.indexOf(item) === -1;
});
不幸的是,出于某种原因,索引始终为 -1,因此没有任何内容被删除。 一些 console.log-s
console.log(item);
console.log(a);
console.log(a.indexOf(item));
,这是数据的样子:
Resource {id: 4, name: "jack"}
[Resource, Resource, Resource, Resource, $promise: Promise, $resolved: true]
-1
最佳答案
你可以这样做
// 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;
});
关于javascript - 使用 Jquery 或 JavaScript 从对象数组中删除对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28541996/