我有2个数组对象,我想得到它们之间的区别,如下所示:
array1 = [{"name":"MPCC","id":"tool:mpcc"}, {"name":"APP","id":"tool:app"}, {"name":"AII","id":"tool:aii"}, {"name":"VZZ","id":"tool:vzz"}, {"name":"USU","id":"tool:usu"}]
array2 = [{"name":"APP","id":"tool:app"}, {"name":"USU","id":"tool:usu"}]
result = [{"name":"MPCC","id":"tool:mpcc"}, {"name":"AII","id":"tool:aii"}, {"name":"VZZ","id":"tool:vzz"}]
这是代码:
$scope.initial = function(base, userData){
var result = [];
angular.forEach( base, function(baseItem) {
angular.forEach( userData, function( userItem ) {
if ( baseItem.id !== userItem.id ) {
if (result.indexOf(baseItem) < 0) {
result.push(baseItem);
}
}
});
});
return result;
}
$scope.initial(array1, array2);
上面的代码的问题是我没有得到想要的结果。请让我知道出了什么问题。
最佳答案
那与Angular无关。
您可以执行以下操作:
var result = array1.filter(function(item1) {
for (var i in array2) {
if (item1.id === array2[i].id) { return false; }
};
return true;
});
或使用ES6语法:
var result = array1.filter(i1 => !array2.some(i2 => i1.id === i2.id));