Skip to content Skip to sidebar Skip to footer

Deep Searching Through A Collection With Lodash

I have an array with objects like so: [ { phase: 1, fields: [ { id: 1, type: 'string' }, { id: 2, type: 'date' } ] }, { phase: 2, fields: [ { id: 3, type: 'date' }, { id:

Solution 1:

You can use javascript reduce function and use where in it :

var elements = array.reduce(function(previous, current) {
    return previous.concat(_.where(current.fields, { type : 'date' }));
}, []);

Lodash version :

var elements = _.reduce(array, function(previous, current) {
    return previous.concat(_.where(current.fields, { type : 'date' }));
}, []);

Solution 2:

Here's a lodash chaining approach:

_(coll)
  .pluck('fields')
  .flatten()
  .filter({ type: 'date' })
  .value();

The pluck() call builds an array of all the field values, which are also arrays. This is why we call flatten() next - to make one big array. Then it's easy to use filter() to get what you need.

Post a Comment for "Deep Searching Through A Collection With Lodash"