Find object by id in an array of JavaScript objects

Question:
---------

I've got an array:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
I'm unable to change the structure of the array. I'm being passed an id of 45, and I want to get 'bar' for that object in the array.



Solution:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];

var found = $.map(myArray, function(val) {
    return val.id == '45' ? val.foo : null;
});

alert(found.length + "\n" + found[0]);

No comments:

Post a Comment