我有两个对象数组。
var arr1 = [{id: "145", firstname: "dave", lastname: "jones"},
{id: "135", firstname: "mike",lastname: "williams"},
{id: "148", firstname: "bob",lastname: "michaels"}];
var arr2 = [{id: "146", firstname: "dave", lastname: "jones"},
{id: "135", firstname: "mike", lastname: "williams"},
{id: "148", firstname: "bob", lastname: "michaels"}];
我希望能够找到只存在于其中一个数组中的id所对应的对象,之后将这些对象输出到控制台或者放入一个新的数组中。
因此,我希望最终能得到:
var arr1 = [{id: "145", firstname: "dave", lastname: "jones"}]
var arr2 = [{id: "146", firstname: "dave", lastname: "jones"}]
我尝试使用forEach循环并从数组中切除匹配的id
arr1.forEach(function(element1, index1) {
let arr1Id = element1.id;
arr2.forEach(function(element2, index2) {
if (arr1Id === element2.id) {
arr1.splice(element1, index1)
arr2.splice(element2, index2)
};
});
});
console.log(arr1);
console.log(arr2);
但我最终得到了
arr1
[ { id: '135', firstname: 'mike', lastname: 'williams' },
{ id: '148', firstname: 'bob', lastname: 'michaels' } ]
arr2
[ { id: '135', firstname: 'mike', lastname: 'williams' },
{ id: '148', firstname: 'bob', lastname: 'michaels' } ]
Array.filter
,它是专门设计用来做这种工作的。 - apple apple{ id: string, firstname: string, lastname: string }
的对象并返回true
(保留)或false
(排除)的函数。 - apple apple