Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question

27 Answers 27

up vote 1178 down vote accepted

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 e.id == 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) {
  // not found
} else if (result.length == 1) {
  // access the foo property using result[0].foo
} else {
  // multiple items found
}
share|improve this answer
80  
It'd be safer to use === instead of ==, to avoid weird issues with JavaScript's == operator. – Vicky Chijwani Dec 11 '12 at 12:03
9  
@VickyChijwani: Are there any issues when comparing a string to a string? – Guffa Dec 11 '12 at 12:17
26  
Well, if you're absolutely sure that both e.id and id will be strings, I suppose it's ok to use ==. But if you're not sure, you might face problems (since '' == 0 is true but '' === 0 is false). Not to mention === seems to be faster (stackoverflow.com/questions/359494/…). – Vicky Chijwani Dec 11 '12 at 13:19
72  
Basically I always use === because it works exactly like == in other programming languages. I consider == to be non-existent in JavaScript. – Vicky Chijwani Dec 11 '12 at 13:27
5  
@de. Many answers here provide the intended behavior when looking up unique values; you can essentially recognize them by the fact that they return or break from their loop early (or instruct a lower-level construct to stop iterating). See JaredPar's answer for a canonical example, and Aaronius's comment on that answer for the same insight. In general, people differentiate between "filter" and "find" functions in this way, but terminology varies. Though more efficient, this is still a linear search, so if you want to use a hash table, see Aaron Digulla's answer (beware of impl. details). – tne Mar 12 '14 at 11:41

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.

share|improve this answer
5  
Exactly what I was looking for. Funny how I was trying to over-complicate it by trying to loop through each time, removing each item from the list as I found it when I only needed to mutate the received data from CouchDB and get it into a format that is useful for my needs. +1 sir! – slickplaid Feb 7 '13 at 17:18
5  
this is smart. I can't imagine how others were convinced by looking all over the array for each use. – Aladdin Mhemed Feb 20 '13 at 5:52
4  
As long as you don't rely on the order of properties: stackoverflow.com/questions/4886314/… – Marle1 Nov 5 '14 at 16:28
    
Is using a break; in the loop a good option / improvement if you know there is only one object to find ? – irJvV Sep 24 '15 at 13:09
3  
@irJvV: No, that doesn't make sense at all. The code above is useful if you need to do many lookups. If you look just once, then creating a lookup object is a waste of time. – Aaron Digulla Sep 24 '15 at 13:40

Underscore.js has a nice method for that:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},etc.]
obj = _.find(myArray, function(obj) { return obj.id == '45' })
share|improve this answer
34  
For the record, Lo-Dash (which is often demonstrably more performant than Underscore) has a similar method. Docs here: lodash.com/docs#find – user456584 Jan 16 '14 at 23:22
1  
@TobiasBeuving, underscore and lodash are both javascript libraries, so is jquery. It's all just javascript ;) – blushrt Feb 23 '15 at 0:57
4  
@TobiasBeuving I didn't interpret the OP meant 'native'. – GijsjanB Mar 16 '15 at 8:37
1  
It looks like 55+ people are happy this answer is in this thread – Ben Taliadoros Apr 23 '15 at 16:41
12  
Since my team was already using Underscore.js, this answer provided a nice solution for me. Often times, answers that are outside of the bounds of the original question are still helpful to others, so I don't see the point of discouraging someone from thinking outside the box of the original post. – Avalanchis Jul 31 '15 at 18:27

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 v.id === '45'; // Filter out the appropriate one
})[0].foo; // Get result and access the foo property
share|improve this answer
    
I'm curious, is there any performance advantage here compared to the usual for? – Igor Zinov'yev Sep 9 '11 at 15:47
    
@Igor Zinov'yev: Yes, there certainly are performance impacts with those ES5 array tools. A separate function is executed for each element, so it won't be really fast compared to a direct for loop. – pimvdb Sep 9 '11 at 15:48
    
So you're saying that it would be slower? Also, it will always scan the whole array, as far as I can see, whereas the for loop will terminate on the first match. – Igor Zinov'yev Sep 9 '11 at 15:50
4  
@Igor Zinov'yev: Yes it's a naive solution, I admit. – pimvdb Sep 9 '11 at 15:53
    
If you need support for IE8, just drop this in: stackoverflow.com/questions/7153470/… – Adam Grant Jul 17 '13 at 21:12
myArray.find(x => x.id === '45').foo

From MDN:

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


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

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

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

myArray.filter(x => x.id === '45').map(x => x.foo)

Side note: methods like find() or filter(), and arrow functions are not supported by all browsers, but it doesn't mean that you can't use these features right now. Just use Babel—it transforms ES6 code into ES5.

share|improve this answer
    
For multiple testing conditions would it therefore be something like: myArray.find(x => x.id === '45' && x.color == 'red').foo – Apqu Oct 20 '16 at 10:33
7  
Calling other methods obsolete and then saying that you need to use a translator (Babel) to translate your code into something that can be used across all current browsers is intentionally deceptive. It means your code does not work on current browsers, not that other solutions are obsolete. Sure, in 5 or 10 years, when compatibility with IE11 is no longer a consideration for most live code, then a solution using these features may be better. But it is not better now, and other answers are not obsolete. – Makyen Oct 23 '16 at 16:04

ECMAScript 6 provides the find-method on arrays. On your example, you’d use it like so:

myArray.find(function (d) {
    return d.id === 45;
}).foo;

// bar

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

share|improve this answer
1  
Probably cause it still seems very experimental and not many browsers support it, developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – lejonl Feb 19 '14 at 22:57

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;
}
share|improve this answer
16  
This wasn't worthy of its own answer, but in modern browsers this solution can be written as: jsfiddle.net/rwaldron/j3vST – Rick Sep 9 '11 at 15:50
9  
If you're going for efficiency, note that this example is likely faster than using filter() (see Rick's example) since this one returns once it finds the first matching item whereas filter() continues running through the full array even after finding a match. This one also doesn't have the cost of creating an additional array or calling a function for each item. – Aaronius Aug 2 '13 at 19:28
3  
@Rick, the most interesting thing about that answer is apparently you can add the firebug console to the output window in jsFiddle. This is so much better than logging and telling someone else to open the console to see the output. Awesome! – KyleMit Aug 29 '14 at 23:48
1  
Since noone has mentioned it so far, I wanted to add that AngularJS also has a filter method. – Eno Feb 4 '15 at 22:37
myArray.filter(function(a){ return a.id == some_id_you_want })[0]
share|improve this answer
1  
Works for IE9+ kangax.github.io/compat-table/es5/#Array.prototype.filter – Justin Aug 21 '15 at 17:56
    
Ployfill for older browsers: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Justin Aug 21 '15 at 18:00

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');
share|improve this answer

You can use filters,

  function getById(id, myArray) {
    return myArray.filter(function(obj) {
      if(obj.id == id) {
        return obj 
      }
    })[0]
  }

get_my_obj = getById(73, myArray);
share|improve this answer
1  
@TobiasBeuving - The one using Array.find() is plain JS too and should stop on the first find so will be more efficient. – Adrian Lynch Oct 7 '15 at 20:19

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 val.id == 45 ? val.foo : null;
});

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

Working example: http://jsfiddle.net/hunter/Pxaua/

share|improve this answer
1  
I forgot about the fact that jQuery's map automatically removes null elements. It sounds misleading to me and to the common concept of map, as the result is not of the same length of the original collection. – MaxArt Sep 5 '14 at 14:30

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==id && a) || (b.id == id && b)
});

returns the object element if found, otherwise false

share|improve this answer
    
Just a note, Array.reduce is not supported in IE8 and under. – Burn_E99 Mar 9 '16 at 23:29

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[i.id]=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: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map

share|improve this answer

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");
share|improve this answer
12  
Don't modify objects you don't own. – Gothdo Feb 14 '16 at 21:15

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:

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

share|improve this answer
1  
Well, it is evil, since it may happen that new EcmaScript versions may introduce new methods with the same name. And guess what, this is exactly what happened with find. My suggestion is that if you want to extend native prototypes, always use more specific names, leaving the simplest ones to future standard developments. – MaxArt Sep 5 '14 at 14:21
    
this comment is nearly 2 years old and today I would rather use lodash anyways. However if you want you can read about this topic on the sugarjs website. They take a good stand to your opinion: sugarjs.com/native – deepflame Sep 22 '14 at 12:19
1  
The op did specifically ask for a javascript or jquery solution – Tobias Beuving Feb 22 '15 at 14:41

Building on the accepted answer:

jQuery:

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

Or CoffeeScript:

foo = $.grep myArray, (e) -> e.id == foo_id
myArray.pop foo
share|improve this answer

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 (test.id === id) 
            return test[key]
    }
    // return undefined if no matching id is found in array
    return;
}

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'
share|improve this answer

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 
	array[indexer[id]].property

share|improve this answer
    
Used same solution as fastest for finding items in array. But parseInt is redundant here. – aleha Sep 25 '16 at 17:30

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 val.id === id;
    });

    // Filter returns an array, and we just want the matching item.
    return obj[0];
}
share|improve this answer

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 obj.id === 45;
});
share|improve this answer
2  
Almost. bFound is just a boolean that is true iff an element satisfies the required condition. – MaxArt Sep 2 '14 at 12:29

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.

share|improve this answer

Use:

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

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

            retObj = obj;
            return false;
        }
    });
return retObj;

It should return an object by id.

share|improve this answer
    
you could shorten your code by using return obj.id === 5 ? obj : false; I use $.each a lot for iterating over arrays. – marcel Apr 8 '14 at 6:53
    
@marcel: That won't work. As returning false will end the loop, it would only find the object if it was the first item in the array. – Guffa Apr 5 '15 at 19:43

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) {
            ret.push(that[index]);
        }
    });
    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.

share|improve this answer
2  
Don't modify objects you don't own. – Gothdo Feb 14 '16 at 21:15
    
@Gothdo I Agree. If someone didn't know function will return the object, rather than an array may get a mistake, but I think it depends on users. – soytian Feb 15 '16 at 3:55

Shortest,

var theAnswerObj = _.findWhere(array, {id : 42});
share|improve this answer
1  
This requires using the underscore library, the OP asked for a plain javascript or jQuery solution – Tobias Beuving Feb 22 '15 at 14:36
1  
once you include underscore, this is not a short answer! – Tim Ogilvy Apr 17 '15 at 18:02

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=[]
  axesOptions.each(function(item){
    if(item.field_type == choice)
        fields= hashToArray(item.fields)
  });
  return fields;
}
share|improve this answer

Use the filter method of jQuery:

 $(myArray).filter(function()
 {
     return this.id == desiredId;
 }).first();

That will return the first element with the specified Id.

It also has the benefit of a nice C# LINQ looking format.

share|improve this answer
4  
The filter method is intended for elements, not arrays. Use the grep method instead. – Guffa Sep 9 '11 at 15:56

My way to find index of array:

index = myArray.map(getAdapterId).indexOf(id);
getAdapterId: function(item) {
  return item.id;
}

// to get foo property use index
myArray[index].foo

//If you want to use ES6
index = myArray.map((i) => i.id).indexOf(45)
myArray[index].foo
share|improve this answer

protected by TigerhawkT3 Oct 24 '16 at 8:50

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.