Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an array of objects have a key value using underscore

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) });
like image 607
underscore666 Avatar asked May 22 '12 08:05

underscore666


2 Answers

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';
} );
like image 183
Florian Margaine Avatar answered Sep 23 '22 21:09

Florian Margaine


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];
        });
    });
};
like image 2
Marcin Avatar answered Sep 24 '22 21:09

Marcin