Categories
arrays javascript javascript-objects

Find object by id in an array of JavaScript objects

1980

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?

0

    1946

    Use the find() method:

    myArray.find(x => x.id === '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 => x.id === '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 => x.id === '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 => x.id === '45').map(x => x.foo);
    

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

    12

    • 5

      For multiple testing conditions would it therefore be something like: myArray.find(x => x.id === ’45’ && x.color == ‘red’).foo

      – Apqu

      Oct 20, 2016 at 10:33

    • 5

      For me, best answer so far. Doesn’t need jQuery neither creating new auxiliar arrays.

      – Canta

      Nov 13, 2017 at 17:38

    • 1

      filter actually has support back to IE9!

      – Leland

      Mar 14, 2019 at 16:54

    • 10

      myArray.find(x => x.id === ’45’).foo; throws an exception if there is no object with an id of ’45’.

      Apr 10, 2019 at 17:34

    • 2

      Can I add multiple condition inside the find method?

      – Si8

      Dec 22, 2020 at 2:51

    1493

    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) {
      // no result found
    } else if (result.length === 1) {
      // property found, access the foo property using result[0].foo
    } else {
      // multiple items found
    }
    

    13

    • 133

      It’d be safer to use === instead of ==, to avoid weird issues with JavaScript’s == operator.

      Dec 11, 2012 at 12:03

    • 11

      @VickyChijwani: Are there any issues when comparing a string to a string?

      – Guffa

      Dec 11, 2012 at 12:17

    • 41

      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/…).

      Dec 11, 2012 at 13:19


    • 108

      Basically I always use === because it works exactly like == in other programming languages. I consider == to be non-existent in JavaScript.

      Dec 11, 2012 at 13:27

    • 6

      @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, 2014 at 11:41

    373

    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.

    13

    • 6

      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!

      Feb 7, 2013 at 17:18

    • 5

      this is smart. I can’t imagine how others were convinced by looking all over the array for each use.

      Feb 20, 2013 at 5:52

    • 4

      As long as you don’t rely on the order of properties: stackoverflow.com/questions/4886314/…

      – Marle1

      Nov 5, 2014 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, 2015 at 13:09

    • 8

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

      Sep 24, 2015 at 13:40