在 JavaScript 中根据另一个包含对象的数组过滤包含对象的数组
javascriptweb developmentfront end technologyobject oriented programming
假设我们有两个像这样的对象数组 −
const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}]; const arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];
我们需要编写一个 JavaScript 函数,该函数接受两个这样的数组。我们的函数应返回第一个数组(本例中为 arr1)的新过滤版本,该版本仅包含具有 name 属性且未包含在第二个数组(本例中为 arr2)中具有相同 name 属性的对象。
因此,本例中的输出应如下所示 −
const output = [{id:'2',name:'B'},{id:'4',name:'D'}];
示例
其代码为 −
const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}]; const arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}]; const filterByReference = (arr1, arr2) => { let res = []; res = arr1.filter(el => { return !arr2.find(element => { return element.id === el.id; }); }); return res; } console.log(filterByReference(arr1, arr2));
输出
控制台中的输出将是 −
[ { id: '2', name: 'B' }, { id: '4', name: 'D' } ]