14

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) });

2 Answers 2

49

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';
} );
Sign up to request clarification or add additional context in comments.

1 Comment

How about checking that there is one such object in the array?
2

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];
        });
    });
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.