How can check if an array of objects have a key value using underscore.
Example:
var objects = [
{id:1, name:'foo'},
{id:2, name:'bar'}
]
check(objects, {name: foo}) // true
I think it should be made using map:
_.map(objects, function(num, key){ console.log(num.name) });
You can use some
for this.
check = objects.some( function( el ) {
return el.name === 'foo';
} );
check
is true
if the function returned true
once, otherwise it's false
.
Not supported in IE7/8 however. You can see the MDN link for a shim.
For the underscore library, it looks like it's implemented too (it's an alias of any
). Example:
check = _.some( objects, function( el ) {
return el.name === 'foo';
} );
Use find
http://underscorejs.org/#find
var check = function (thelist, props) {
var pnames = _.keys(props);
return _.find(thelist, function (obj) {
return _.all(pnames, function (pname) {
return obj[pname] == props[pname];
});
});
};
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