I have the following array of values:
[
{
id: 1,
field: 'map'
},
{
id: 2,
field: 'dog'
},
{
id: 3,
field: 'map'
}
]
I need to find out elements with field equals dog
and map
. I know I could use the _.filter
method and pass an iterator function, but what I want to know is whether or not there's a better solution to this issue where I could pass search field and possible values. Could someone provide a better way of doing so?
EDIT::
I could use the following approach:
_.where(array, {field: 'dog'})
But here I may check only one clause
_.filter(data, function(item){ return item.field === 'map' || item.field === 'dog'; })
If you want to create a function which accepts field
and values
it can look like this:
function filter(data, field, values) {
_.filter(data, function(item){ return _.contains(values, item[field]); })
}
Just pass your filter criteria as the third parameter of _.filter(list, predicate, [context])
which is then set as the context
(this
) of the iterator:
var data = [
{ id: 1, field: 'map' },
{ id: 2, field: 'dog' },
{ id: 3, field: 'blubb' }
];
var filtered = _.filter(
data,
function(i) { return this.values.indexOf(i.field) > -1; },
{ "values": ["map", "dog"] } /* "context" with values to look for */
);
console.log(filtered);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With