从数组中排除给定对象

Exclude given objects from array

我有以下数组。我试图在处理过程中从这个数组中排除某些对象。

例如。我想排除类型 'dog' 并且只使用任何类型为 duck.

的对象

我想使用 underscore/lodash 执行此操作,但如果需要,我会使用纯 JS。

animals: [
  {
    type: 'duck',
    name: 'quack',
  },
  {
    type: 'duck',
    name: 'quieck',
  },
  {
    type: 'dog',
    name: 'bark',
  },
]

我想你的数组代表变量 animals。您可以使用 Array.prototype.filter() 函数。如果你想要所有的鸭子:

const animals = [
    { type: 'duck', name: 'quack' },
    { type: 'duck', name: 'quieck' },
    { type: 'dog', name: 'bark' },
];
const ducks = animals.filter(o => o.type === 'duck');

或者如果您想排除所有狗:

const withoutDogs = animals.filter(o => o.type !== 'dog');

我使用的是 ES6 语法。 ES5 等效项为:

var ducks = animals.filter(function(o) { return o.type === 'duck' });

Underscore/LoDash 方式,就是

var result = _.where(animals, {type: 'duck'});