Find object by id in an array of JavaScript objects

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?

Use the find() method:

myArray.find(x => === '45').foo;

From MDN:

The find() method returns the first value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned.

If you want to find its index instead, use findIndex():

myArray.findIndex(x => === '45');

From MDN:

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.

If you want to get an array of matching elements, use the filter() method instead:

myArray.filter(x => === '45');

This will return an array of objects. If you want to get an array of foo properties, you can do this with the map() method:

myArray.filter(x => === '45').map(x =>;

Side note: methods like find() or filter(), and arrow functions are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel (with the polyfill).

As you are already using jQuery, you can use the grep function which is intended for searching an array:

var result = $.grep(myArray, function(e){ return == id; });

The result is an array with the items found. If you know that the object is always there and that it only occurs once, you can just use result[0].foo to get the value. Otherwise you should check the length of the resulting array. Example:

if (result.length === 0) {
  // no result found
} else if (result.length === 1) {
  // property found, access the foo property using result[0].foo
} else {
  // multiple items found

Another solution is to create a lookup object:

var lookup = {};
for (var i = 0, len = array.length; i < len; i++) {
    lookup[array[i].id] = array[i];

... now you can use lookup[id]...

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.

ECMAScript 2015 provides the find() method on arrays:

var myArray = [
 {id:1, name:"bob"},
 {id:2, name:"dan"},
 {id:3, name:"barb"},

// grab the Array item which matchs the id "2"
var item = myArray.find(item => === 2);

// print

It works without external libraries. But if you want older browser support you might want to include this polyfill.

Underscore.js has a nice method for that:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},etc.]
obj = _.find(myArray, function(obj) { return == '45' })

I think the easiest way would be the following, but it won't work on Internet Explorer 8 (or earlier):

var result = myArray.filter(function(v) {
    return === '45'; // Filter out the appropriate one
})[0].foo; // Get result and access the foo property

Try the following

function findById(source, id) {
  for (var i = 0; i < source.length; i++) {
    if (source[i].id === id) {
      return source[i];
  throw "Couldn't find object with id: " + id;

myArray.filter(function(a){ return == some_id_you_want })[0]

A generic and more flexible version of the findById function above:

// array = [{key:value},{key:value}]
function objectFindByKey(array, key, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i][key] === value) {
            return array[i];
    return null;

var array = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
var result_obj = objectFindByKey(array, 'id', '45');

You can get this easily using the map() function:

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

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

//found[0] == "bar";

Working example:

You can use filters,

  function getById(id, myArray) {
    return myArray.filter(function(obj) {
      if( == id) {
        return obj 

get_my_obj = getById(73, myArray);

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:

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

var lookup = items.reduce((o,i)=>o[]=o,{});

you can then get at items in fixed time like this :

var bar = o[id];

You might also consider using a Map instead of an object as the lookup:

Using native Array.reduce

var array = [ {'id':'73' ,'foo':'bar'} , {'id':'45' ,'foo':'bar'} , ];
var id = 73;
var found = array.reduce(function(a, b){
    return ( && a) || ( == id && b)

returns the object element if found, otherwise false

Here's how I'd go about it in pure JavaScript, in the most minimal manner I can think of that works in ECMAScript 3 or later. It returns as soon as a match is found.

var getKeyValueById = function(array, key, id) {
    var testArray = array.slice(), test;
    while(test = testArray.pop()) {
        if ( === id) {
            return test[key];
    // return undefined if no matching id is found in array

var myArray = [{'id':'73', 'foo':'bar'}, {'id':'45', 'foo':'bar'}]
var result = getKeyValueById(myArray, 'foo', '45');

// result is 'bar', obtained from object with id of '45'

If you do this multiple times, you may set up a Map (ES6):

const map = new Map( => [, el]) );

Then you can simply do:


More generic and short

function findFromArray(array,key,value) {
        return array.filter(function (element) {
            return element[key] == value;

in your case Ex. var element = findFromArray(myArray,'id',45) that will give you the whole element.

You may try out Sugarjs from

It has a very sweet method on Arrays, .find. So you can find an element like this:

array.find( {id: 75} );

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...

Building on the accepted answer:


var foo = $.grep(myArray, function(e){ return === foo_id})

Or CoffeeScript:

foo = $.grep myArray, (e) -> == foo_id
myArray.pop foo

Iterate over any item in the array. For every item you visit, check that item's id. If it's a match, return it.

If you just want teh codez:

function getId(array, id) {
    for (var i = 0, len = array.length; i < len; i++) {
        if (array[i].id === id) {
            return array[i];
    return null; // Nothing found

And the same thing using ECMAScript 5's Array methods:

function getId(array, id) {
    var obj = array.filter(function (val) {
        return === id;

    // Filter returns an array, and we just want the matching item.
    return obj[0];

As long as the browser supports ECMA-262, 5th edition (December 2009), this should work, almost one-liner:

var bFound = myArray.some(function (obj) {
    return === 45;

You can do this even in pure JavaScript by using the in built "filter" function for arrays:

Array.prototype.filterObjects = function(key, value) {
    return this.filter(function(x) { return x[key] === value; })

So now simply pass "id" in place of key and "45" in place of value, and you will get the full object matching an id of 45. So that would be,

myArr.filterObjects("id", "45");

Use Array.prototype.filter() function.



var jsonObj =[
  "name": "Me",
  "info": {
   "age": "15",
   "favColor": "Green",
   "pets": true
  "name": "Alex",
  "info": {
   "age": "16",
   "favColor": "orange",
   "pets": false
  "name": "Kyle",
  "info": {
   "age": "15",
   "favColor": "Blue",
   "pets": false


var getPerson = function(name){
    return jsonObj.filter(function(obj) {
      return === name;

Recently, I have to face the same thing in which I need to search the string from a huge array.

After some search I found It'll be easy to handle with simple code:


var items = mydata.filter(function(item){
    return item.word.toLowerCase().startsWith( 'gk );


Serach from 20k strings

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

	var indexer = {};
	for (var i = 0; i < array.length; i++) {
	    indexer[array[i].id] = parseInt(i);
	//Then you can access object properties in your array using 

We can use Jquery methods $.each()/$.grep()

var data= [];
$.each(array,function(i){if(n !== 5 && i > 4){data.push(item)}}


var data = $.grep(array, function( n, i ) {
  return ( n !== 5 && i > 4 );

use ES6 syntax:

Array.find, Array.filter, Array.forEach,

Or use Lodash, Underscore


var retObj ={};
$.each(ArrayOfObjects, function (index, obj) {

        if ( === '5') { // id.toString() if it is int

            retObj = obj;
            return false;
return retObj;

It should return an object by id.

This solution may helpful as well:

Array.prototype.grep = function (key, value) {
    var that = this, ret = [];
    this.forEach(function (elem, index) {
        if (elem[key] === value) {
    return ret.length < 2 ? ret[0] : ret;
var bar = myArray.grep("id","45");

I made it just like $.grep and if one object is find out, function will return the object, rather than an array.

Starting from aggaton's answer, this is a function that actually returns the wanted element (or null if not found), given the array and a callback function that returns a truthy value for the "correct" element:

function findElement(array, callback) {
    var elem;
    return array.some(function(e) {
        if (callback(e)) {
            elem = e;
            return true;
    }) ? elem : null;

Just remember that this doesn't natively work on IE8-, as it doesn't support some. A polyfill can be provided, alternatively there's always the classic for loop:

function findElement(array, callback) {
    for (var i = 0; i < array.length; i++)
        if (callback(array[i])) return array[i];
    return null;

It's actually faster and more compact. But if you don't want to reinvent the wheel, I suggest using an utility library like underscore or lodash.


var theAnswerObj = _.findWhere(array, {id : 42});

Consider "axesOptions" to be array of objects with an object format being {:field_type => 2, :fields => [1,3,4]}

function getFieldOptions(axesOptions,choice){
  var fields=[]
    if(item.field_type == choice)
        fields= hashToArray(item.fields)
  return fields;

As others have pointed out, .find() is the way to go when looking for one object within your array. However, if your object cannot be found using this method, your program will crash:

const myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
const res = myArray.find(x => === '100').foo; // Uh oh!
"Uncaught TypeError: Cannot read property 'foo' of undefined"

This can be fixed by checking whether the result of .find() is defined before using using .foo on it. Modern JS allows us to do this easily with optional chaining, returning undefined if the object cannot be found, rather than crashing your code:

const myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
const res = myArray.find(x => === '100')?.foo; // No error!
console.log(res); // undefined when the object cannot be found


Today 2020.06.20 I perform test on MacOs High Sierra on Chrome 81.0, Firefox 77.0 and Safari 13.1 for chosen solutions.

Conclusions for solutions which use precalculations

Solutions with precalculations (K,L) are (much much) faster than other solutions and will not be compared with them - probably they are use some special build-in browser optimisations

  • surprisingly on Chrome and Safari solution based on Map (K) are much faster than solution based on object {} (L)
  • surprisingly on Safari for small arrays solution based on object {} (L) is slower than traditional for (E)
  • surprisingly on Firefox for small arrays solution based on Map (K) is slower than traditional for (E)

Conclusions when searched objects ALWAYS exists

  • solution which use traditional for (E) is fastest for small arrays and fast for big arrays
  • solution using cache (J) is fastest for big arrays - surprisingly for small arrays is medium fast
  • solutions based on find (A) and findIndex (B) are fast for small arras and medium fast on big arrays
  • solution based on $.map (H) is slowest on small arrays
  • solution based on reduce (D) is slowest on big arrays

enter image description here

Conclusions when searched objects NEVER exists

  • solution based on traditional for (E) is fastest on small and big arrays (except Chrome-small arrays where it is second fast)
  • solution based on reduce (D) is slowest on big arrays
  • solution which use cache (J) is medium fast but can be speed up if we save in cache also keys which have null values (which was not done here because we want to avoid unlimited memory consumption in cache in case when many not existing keys will be searched)

enter image description here


For solutions

  • without precalculations: A B C D E F G H I J (the J solution use 'inner' cache and it speed depend on how often searched elements will repeat)
  • with precalculations K L

I perform four tests. In tests I want to find 5 objects in 10 loop iterations (the objects ID not change during iterations) - so I call tested method 50 times but only first 5 times have unique id values:

  • small array (10 elements) and searched object ALWAYS exists - you can perform it HERE
  • big array (10k elements) and searched object ALWAYS exist - you can perform it HERE
  • small array (10 elements) and searched object NEVER exists - you can perform it HERE
  • big array (10k elements) and searched object NEVER exists - you can perform it HERE

Tested codes are presented below

function A(arr, id) {
  return arr.find(o=>;

function B(arr, id) {
  let idx= arr.findIndex(o=>;
  return arr[idx];

function C(arr, id) {
  return arr.filter(o=>[0];

function D(arr, id) {
  return arr.reduce((a, b) => ( && a) || ( == id && b));

function E(arr, id) {
  for (var i = 0; i < arr.length; i++) if (arr[i].id==id) return arr[i];
  return null;

function F(arr, id) {
  var retObj ={};
  $.each(arr, (index, obj) => {
    if ( == id) { 
      retObj = obj;
      return false;
  return retObj;

function G(arr, id) {
  return $.grep(arr, e=> == id )[0];

function H(arr, id) {
  return $.map(myArray, function(val) {
    return == id ? val : null;

function I(arr, id) {
  return _.find(arr, o =>;

let J = (()=>{
  let cache = new Map();
  return function J(arr,id,el=null) { 
    return cache.get(id) || (el=arr.find(o=>, cache.set(id,el), el);

function K(arr, id) {
  return mapK.get(id)

function L(arr, id) {
  return mapL[id];

// -------------
// -------------

console.log('Find id=5');

myArray = [...Array(10)].map((x,i)=> ({'id':`${i}`, 'foo':`bar_${i}`}));
const mapK = new Map( => [, el]) );
const mapL = {}; myArray.forEach(el => mapL[]=el);

[A,B,C,D,E,F,G,H,I,J,K,L].forEach(f=> console.log(`${}: ${JSON.stringify(f(myArray, '5'))}`));

console.log('Whole array',JSON.stringify(myArray));
<script src=""></script>
<script src=""></script>

This snippet only presents tested codes

Example tests results for Chrome for small array where searched objects always exists

enter image description here