I have the below array. I am attempting to exclude certain objects from this array in processing.
For example. I would like to exclude the type 'dog' and only use any object that is of type duck.
I'd like to do this using underscore/lodash but will use plain JS if need be.
animals: [
{
type: 'duck',
name: 'quack',
},
{
type: 'duck',
name: 'quieck',
},
{
type: 'dog',
name: 'bark',
},
]
I suppose your array represents variable animals
. You can use Array.prototype.filter() function. If you want all ducks:
const animals = [
{ type: 'duck', name: 'quack' },
{ type: 'duck', name: 'quieck' },
{ type: 'dog', name: 'bark' },
];
const ducks = animals.filter(o => o.type === 'duck');
or if you want to exclude all dogs:
const withoutDogs = animals.filter(o => o.type !== 'dog');
I used ES6 syntax. ES5 equivalent would be:
var ducks = animals.filter(function(o) { return o.type === 'duck' });
Underscore / LoDash方法只是
var result = _.where(animals, {type: 'duck'});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.