如何比较两个数组,以便它们返回不匹配的对象数组。上面的条目返回给我一个包含在一个和另一个中的对象数组。如何从 result1
返回不在 result2
数组中的对象数组?
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));
此处演示:https://stackblitz.com/edit/js-qavyib
var result1 = [
{id:1, name:'Sandra', type:'user', username:'sandra'},
{id:2, name:'John', type:'admin', username:'johnny2'},
{id:3, name:'Peter', type:'user', username:'pete'},
{id:4, name:'Bobby', type:'user', username:'be_bob'}
];
var result2 = [
{id:2, name:'John', email:'johnny@example.com'},
{id:4, name:'Bobby', email:'bobby@example.com'}
];
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));
console.log(result);
/*
0: Object
id: 2
name: "John"
type: "admin"
username: "johnny2"
1: Object
id: 4
name: "Bobby"
type: "user"
username: "be_bob"*/
最佳答案
检查 result2
中的 .every
项目没有相同的 id
:
var result1 = [
{id:1, name:'Sandra', type:'user', username:'sandra'},
{id:2, name:'John', type:'admin', username:'johnny2'},
{id:3, name:'Peter', type:'user', username:'pete'},
{id:4, name:'Bobby', type:'user', username:'be_bob'}
];
var result2 = [
{id:2, name:'John', email:'johnny@example.com'},
{id:4, name:'Bobby', email:'bobby@example.com'}
];
let result = result1.filter(o1 => result2.every(o2 => o1.id !== o2.id));
console.log(result);
关于javascript - 如何从 `result1` 返回不在 result2 数组中的对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58667124/