E.g:
const array1 = [
{id: 1, name: 'Bob', age: 29},
{id: 2, name: 'Anne', age: 18},
{id: 3, name: 'Dave', age: 29},
{id: 4, name: 'Barry', age: 50},
{id: 5, name: 'Jill', age: 35},
];
const array2 = [29, 50];
我想浏览array1
并删除object.age
位于array2
的所有对象。我的一次性用lodash但他们的文件让我感到困惑......
答案 0 :(得分:4)
您可以使用Array#filter和Array#includes来获得所需的结果。过滤第一个数组并检查第二个数组是否包含当前项的年龄并反转结果。
const array1 = [
{id: 1, name: 'Bob', age: 29},
{id: 2, name: 'Anne', age: 18},
{id: 3, name: 'Dave', age: 29},
{id: 4, name: 'Barry', age: 50},
{id: 5, name: 'Jill', age: 35},
];
const array2 = [29, 50];
const mapped = array1.filter(item => !array2.includes(item.age));
console.log(mapped);

答案 1 :(得分:2)
如果你可以改变数组(在适当的位置修改)
_.pullAllBy(array1, [{ age: 29 }, { age: 50 }], 'age');
如果你想要一个新阵列:
const newArray = _.differenceBy(array1, [{ age: 29 }, { age: 50 }], 'age');
答案 2 :(得分:1)
使用array.prototype.filter:
var array1 = [
{id: 1, name: 'Bob', age: 29},
{id: 2, name: 'Anne', age: 18},
{id: 3, name: 'Dave', age: 29},
{id: 4, name: 'Barry', age: 50},
{id: 5, name: 'Jill', age: 35},
];
var array2 = [29, 50];
var array1 = array1.filter(e => !array2.includes(e.age));
console.log(array1);