I want to select the objects based on the properties of the objects, but not always the same properties. In other words:
arr = [
{ name: \"joe\", age21
Here's a functional approach that should work for any numbers of properties given the object:
function filter(arr, criteria) {
return arr.filter(function(obj) {
return Object.keys(criteria).every(function(c) {
return obj[c] == criteria[c];
});
});
}
For example:
var arr = [
{ name: 'Steve', age: 18, color: 'red' },
{ name: 'Louis', age: 21, color: 'blue' }, //*
{ name: 'Mike', age: 20, color: 'green' },
{ name: 'Greg', age: 21, color: 'blue' }, //*
{ name: 'Josh', age: 18, color: 'red' }
];
console.log(filter(arr, { age: 21, color: 'blue' }));
//^ {age:21, color:'blue', name:'Louis}
// {age:21, color:'blue', name:'Greg'}
Not sure about your performance issue, but this should be OK.
Edit: You could make this more powerful with regular expressions, something like this:
function filter(arr, criteria) {
return arr.filter(function(obj) {
return Object.keys(criteria).every(function(c) {
return new RegExp(criteria[c]).test(obj[c]);
});
});
}
console.log(filter(arr, { age: /^2\d$/, color: /^(red|blue)$/ }));
//^ Louis, Greg --^-- twenty-something
// ----^---- red OR blue