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.
How do I do this in JavaScript or using jQuery?
You may try out Sugarjs from http://sugarjs.com/.
It has a very sweet method on Arrays,
.find
. So you can find an element like this:You may also pass an object with more properties to it to add another "where-clause".
Note that Sugarjs extends native objects, and some people consider this very evil...
This solution may helpful as well:
I made it just like
$.grep
and if one object is find out, function will return the object, rather than an array.Building on the accepted answer:
jQuery:
Or CoffeeScript:
You can do this even in pure JavaScript by using the in built "filter" function for arrays:
So now simply pass "id" in place of
key
and "45" in place ofvalue
, and you will get the full object matching an id of 45. So that would be,While there are many correct answers here, many of them do not address the fact that this is an unnecessarily expensive operation if done more than once. In an extreme case this could be the cause of real performance problems.
In the real world, if you are processing a lot of items and performance is a concern it's much faster to initially build a lookup:
you can then get at items in fixed time like this :
You might also consider using a Map instead of an object as the lookup: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map