按值过滤对象
Filter object by value
假设我有:
let object1 = [{id: 15, name: name1}, {id: 0, name: name2}, {id: 98, name: name3}];
let object2 = [{id: 2, action: action}, {id: 88, action: action}, {id: 0, action: action}];
身份证号码故意不匹配。
如何从 ID 未出现在对象 2 中的对象 1 中获取名称值?
编辑:我试过了
let results;
for (let i = 0; i < object1.length; i++) {
results = object2.filter(element => { return element.id != object1[i].id } );
}
也试图让它与 .map() 一起工作,但没有成功。
您可以在其中一个数组上使用 filter()
,并使用 find()
从该数组中过滤出其 ID 未出现在另一个数组中的对象。
let oArr1 = [{id: 15, name: "name1"}, {id: 0, name: "name2"}, {id: 98, name: "name3"}];
let oArr2 = [{id: 2, action: "action"}, {id: 88, action: "action"}, {id: 0, action: "action"}];
const result = oArr1.filter(x => !oArr2.find(y => y.id === x.id));
console.log(result);
假设我有:
let object1 = [{id: 15, name: name1}, {id: 0, name: name2}, {id: 98, name: name3}];
let object2 = [{id: 2, action: action}, {id: 88, action: action}, {id: 0, action: action}];
身份证号码故意不匹配。 如何从 ID 未出现在对象 2 中的对象 1 中获取名称值?
编辑:我试过了
let results;
for (let i = 0; i < object1.length; i++) {
results = object2.filter(element => { return element.id != object1[i].id } );
}
也试图让它与 .map() 一起工作,但没有成功。
您可以在其中一个数组上使用 filter()
,并使用 find()
从该数组中过滤出其 ID 未出现在另一个数组中的对象。
let oArr1 = [{id: 15, name: "name1"}, {id: 0, name: "name2"}, {id: 98, name: "name3"}];
let oArr2 = [{id: 2, action: "action"}, {id: 88, action: "action"}, {id: 0, action: "action"}];
const result = oArr1.filter(x => !oArr2.find(y => y.id === x.id));
console.log(result);