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?
Another solution is to create a lookup object:
This is especially interesting if you need to do many lookups.
This won't need much more memory since the IDs and objects will be shared.
I really liked the answer provided by Aaron Digulla but needed to keep my array of objects so I could iterate through it later. So I modified it to
Shortest,
We can use Jquery methods $.each()/$.grep()
var data= []; $.each(array,function(i){if(n !== 5 && i > 4){data.push(item)}}
or
var data = $.grep(array, function( n, i ) { return ( n !== 5 && i > 4 ); });
use ES6 syntax:
Array.find, Array.filter, Array.forEach, Array.map
Or use Lodash https://lodash.com/docs/4.17.10#filter, Underscore https://underscorejs.org/#filter
Using native
Array.reduce
returns the object element if found, otherwise
false
I think the easiest way would be the following, but it won't work on Internet Explorer 8 (or earlier):