Skip to content

Instantly share code, notes, and snippets.

@circa10a
Last active June 30, 2018 21:19
Show Gist options
  • Save circa10a/96465112786384bf37c180b4e22a0428 to your computer and use it in GitHub Desktop.
Save circa10a/96465112786384bf37c180b4e22a0428 to your computer and use it in GitHub Desktop.
Filter an array of objects with key/value pairs
const _ = require('underscore');
arr = [
{
car: "toyota",
color: "blue",
year: 2010,
trans: "auto",
warrantyEnd: "2013"
},
{
car: "toyota",
condition: "good",
color: "green",
year: 2010,
trans: "manual",
warrantyEnd: "2013",
},
{
car: "ford",
color: "yellow",
year: 2012,
trans: "auto",
warrantyEnd: "2015"
}
];
//########################################
// Filter array using same data types
//########################################
filters = {
trans: "manual",
year: 2010,
condition: "good"
};
const filteredResults = _.filter(arr, filters);
console.log(filteredResults);
/* [ { car: 'toyota',
condition: 'good',
color: 'green',
year: 2010,
trans: 'manual',
warrantyEnd: '2013' } ] */
//################################################################
// Filter array using different data types (better for user error)
//################################################################
diffDataTypeFilters = {
trans: "manual",
year: "2010",
condition: "good",
warrantyEnd: 2013
};
// Convert existing array values to strings
const newArr = arr.map(item => _.mapObject(item, val => { return val.toString() }));
// Ensure data/json brought in to only have strings for values
const modifiedFilters = _.mapObject(diffDataTypeFilters, val => { return val.toString() });
// Filter
const newFilteredResults = _.filter(newArr, modifiedFilters);
console.log(newFilteredResults);
/*[ { car: 'toyota',
condition: 'good',
color: 'green',
year: '2010',
trans: 'manual',
warrantyEnd: '2013' } ] */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment