Filtering complex objects with Lodash / Underscore

I was trying to filter a large array of objects by some nested key values in a separate array of objects. I had a few ideas from my old-school tried-and-true thought processes; nested loops, filtering it out inline while displaying (instead of before rendering)… those worked, but both were verbose and uglier to read than I was happy with. I thought there must be a better way for what seems like a fairly common RESTful data set interaction. Underscore has a perfect function called “pluck”.

If you have an array of objects, like:

var options = [
{ value: 1, label: ‘I’ },
{ value: 2, label: ‘II’ },
{ value: 3, label: ‘III’ },
{ value: 4, label: ‘IV’ },

And you have a huge set of data that you want to filter down, like:

var filterMe = [
{ gen: 1, name: ‘Pikachu’, type: ‘Electric’ },
{ gen: 1, name: ‘Charmander’, type: ‘Fire’ },
{ gen: 2, name: ‘Cyndaquil’, type: ‘Fire’ },
{ gen: 3, name: ‘Torchic’, type: ‘Fire’ },

Then doing a pluck() on options for value will give you a nice array:

[1, 2, 3, 4]

So when you do your .map() for filterMe, to get the records where gen matches value in options, all you need is a standard indexOf().

myPluckedArray = _.pluck(options, ‘value’){
if (myPluckedArray.indexOf(obj.gen) > -1){
return obj

To shrink it down even more:{
if (_.pluck(options, ‘value’).indexOf(obj.gen) > -1){
return obj