By thugsb

2011-09-09 15:42:29 8 Comments

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?


@TLbiz 2018-09-25 06:49:04

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

@maheshwaghmare 2019-07-25 10:05:16

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

@Guffa 2011-09-09 15:54:31

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

@Vicky Chijwani 2012-12-11 12:03:01

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

@Guffa 2012-12-11 12:17:43

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

@Vicky Chijwani 2012-12-11 13:19:25

Well, if you're absolutely sure that both 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 (…).

@Vicky Chijwani 2012-12-11 13:27:48

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

@tne 2014-03-12 11:41:55

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

@Guffa 2014-03-12 13:02:07

@tne: Note that there is nothing in the question that specifically says that the id is unique, and that my answer doesn't do that assumption.

@tne 2014-03-12 13:23:27

@Guffa: Indeed, your answer is absolutely correct with regard to the question as it is stated -- I just felt like pointing it out since it'll likely concern many readers who might otherwise miss an opportunity to do the right thing when they can (when the search property contains unique values).

@stevenspiel 2014-10-23 14:25:42

once you have result, just do myArray.pop(result)

@Guffa 2014-10-23 17:15:23

@mr.musicman: What are you trying to accomplish with that? The pop method doesn't take a parameter, so it will just remove the last item from the array and return it.

@Guffa 2015-01-07 09:03:34

@MatíasFidemraizer: The filter method is not supported in older browsers like IE 8, so using a library like jQuery is still a good option if you need it to work for as many as possible.

@Matías Fidemraizer 2015-01-07 09:05:55

@Guffa Who cares about IE8 now. It's an edge case. Since you're answer is the selected as right one, a lot of novice JS devs won't know about filter because of your answer! You've a lot of responsibility :D

@Guffa 2015-01-07 12:08:09

@MatíasFidemraizer: This answer doesn't try to list all possible solutions, it only shows the simplest and most compatible solution in the situation specified in the question. IE 8 is still too common for advocating a solution that doesn't support it, when there is a solution that is as simple and does support it.

@patotoma 2017-09-24 17:41:36

I've created a tiny utility just for this where you can access with O(1) called super-array

@Vu Truong 2016-05-24 02:28:59

My way to find index of array:

index = =>;
item = myArray[index];

@Michał Perłakowski 2016-02-14 21:11:10

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

@Apqu 2016-10-20 10:33:02

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

@Canta 2017-11-13 17:38:03

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

@Govinda Rajbhar 2018-05-30 13:13:31

myArray.find(x => === '45') it does not work on mac PC

@Michał Perłakowski 2018-06-04 17:50:35

@T.J.Crowder I don't think that it's a good idea to copy-paste polyfills from MDN into your code; instead, you should use npm packages with polyfills. And Babel does include polyfills for ES2015+ features, in the babel-polyfill package.

@T.J. Crowder 2018-06-04 18:23:18

@MichałPerłakowski - I did say "(Babel can also include polyfills for some things)" And agreed, polyfilling has moved on since copy-and-paste from MDN. :-)

@ColinWa 2018-10-01 09:22:08

This example uses ECMAScript 6 arrow function. In case of errors when using arrow functions, there are other ways out. See (…‌​) and (…)

@Leland 2019-03-14 16:54:40

filter actually has support back to IE9!

@Frazer Kirkman 2019-04-10 17:34:57

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

@Savan Kaneriya 2018-12-12 06:35:58

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.

@Jonas Wilms 2017-08-08 15:26:35

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

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

Then you can simply do:


@Rúnar Berg 2014-02-10 22:32:16

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.

@lejonl 2014-02-19 22:57:09

Probably cause it still seems very experimental and not many browsers support it,…

@Shaggy 2017-03-06 11:29:30

This can be simplified to myArray.find(d=>;.

@Rúnar Berg 2017-03-06 19:49:23

@Shaggy or even myArray.find(({ id }) => id === 45).foo. But this is an old answer that was written before ES2015 syntax was as well supported as now. @Gothdo’s answer is currently the most up to date in the thread.

@Herbert Peters 2018-04-03 00:57:08

@Shaggy if the .find() returns undefined, then your optimization throws an error. So this solution is can be used only in cases where a match is guaranteed.

@Rúnar Berg 2018-04-03 20:14:54

@HerbertPeters If you want to be sure you can alway null-check, which will be really easy with optional chaining: myArray.find(d => === 45)?.foo.

@Milad Rashidi 2018-08-14 06:16:54

This solution is for ES6 and it doesn't compatible with IE browser.

@Rúnar Berg 2018-08-16 20:25:43

@MiladRashidi Like the answer states there is a polyfill if you want older browser support. Likewise it is easy to rewrite using the older syntax.

@Sumit Ridhal 2017-05-02 15:40:32

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;

@Valay 2017-06-14 21:22:01

how can I search within nested object ? Like pets= false should return two objects.

@Sumit Ridhal 2017-06-17 18:07:58

use .filter method on in nested loop. var getPerson = function(name){ return jsonObj.filter(function(obj) { return { return pets === false; }); }); }

@DagicCross 2018-06-08 02:10:57

you could use es6 style too imo... const filterData = jsonObj.filter(obj => === 'Alex')

@Dan W 2015-02-28 18:04:18

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'

@Tom 2016-03-23 10:24:18

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:

@kaizer1v 2014-10-26 04:39:55

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");

@Michał Perłakowski 2016-02-14 21:15:02

Don't modify objects you don't own.

@pimvdb 2011-09-09 15:46:33

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

@Igor Zinov'yev 2011-09-09 15:47:38

I'm curious, is there any performance advantage here compared to the usual for?

@pimvdb 2011-09-09 15:48:50

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

@Igor Zinov'yev 2011-09-09 15:50:36

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.

@Adam Grant 2013-07-17 21:12:29

If you need support for IE8, just drop this in:…

@Stan 2017-02-23 14:57:44

This code will throw an error if there's no element with that id

@stevenspiel 2014-10-23 14:23:27

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

@soytian 2014-10-22 09:15:19

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.

@Michał Perłakowski 2016-02-14 21:15:29

Don't modify objects you don't own.

@soytian 2016-02-15 03:55:41

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

@aggaton 2014-04-08 17:14:19

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;

@MaxArt 2014-09-02 12:29:56

Almost. bFound is just a boolean that is true iff an element satisfies the required condition.

@volumexxx 2013-02-28 15:03:27


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.

@marcel 2014-04-08 06:53:52

you could shorten your code by using return === 5 ? obj : false; I use $.each a lot for iterating over arrays.

@Guffa 2015-04-05 19:43:34

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

@deepflame 2012-11-06 08:52:01

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

@MaxArt 2014-09-05 14:21:10

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.

@deepflame 2014-09-22 12:19:19

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:

@Tobias Beuving 2015-02-22 14:41:32

The op did specifically ask for a javascript or jquery solution

@hunter 2011-09-09 15:46:35

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:

@MaxArt 2014-09-05 14:30:17

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.

@Zirak 2011-09-09 15:46:34

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];

@laggingreflex 2015-06-04 00:13:49

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

@Burn_E99 2016-03-09 23:29:40

Just a note, Array.reduce is not supported in IE8 and under.

@Danilo Colasso 2015-04-16 17:31:49

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

@Justin 2015-08-21 18:00:21

@Valay 2017-06-14 21:25:37

@Danilo how can I search within nested object ?…

@ramya 2015-03-04 06:06:06

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;

@Manu 2015-01-03 03:52:31


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

@Tobias Beuving 2015-02-22 14:36:25

This requires using the underscore library, the OP asked for a plain javascript or jQuery solution

@Tim Ogilvy 2015-04-17 18:02:17

once you include underscore, this is not a short answer!

@quincyaft 2014-11-19 03:55:57

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 

@aleha 2016-09-25 17:30:16

Used same solution as fastest for finding items in array. But parseInt is redundant here.

@MaxArt 2014-09-02 12:41:43

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.

@Joe Lewis 2013-09-13 09:43:20

You can use filters,

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

get_my_obj = getById(73, myArray);

@Adrian Lynch 2015-10-07 20:19:19

@TobiasBeuving - The one using Array.find() is plain JS too and should stop on the first find so will be more efficient.

@GijsjanB 2012-11-22 12:52:21

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' })

@user456584 2014-01-16 23:22:38

For the record, Lo-Dash (which is often demonstrably more performant than Underscore) has a similar method. Docs here:

@Foreever 2015-10-20 04:00:08

If you are expecting only one object, then using findWhere would be more efficient as after finding one result, the search would not go any further.

@GijsjanB 2015-10-20 09:06:50

@Foreever From the docs of _.find: "The function returns as soon as it finds an acceptable element, and doesn't traverse the entire list."

@will Farrell 2012-07-13 20:34:26

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');

@Aaron Digulla 2011-09-09 15:50:09

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.

@slickplaid 2013-02-07 17:18:37

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!

@Aladdin Mhemed 2013-02-20 05:52:24

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

@Marle1 2014-11-05 16:28:16

As long as you don't rely on the order of properties:…

@irJvV 2015-09-24 13:09:49

Is using a break; in the loop a good option / improvement if you know there is only one object to find ?

@Aaron Digulla 2015-09-24 13:40:47

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

@irJvV 2015-09-24 14:00:30

@AaronDigulla thanks you are right. The lookup replaces the array because the objects from the array are stored under their id in var lookup. To save memory i deleted the original array with array = [ ];

@kfirba 2015-11-02 16:36:25

I love that approach. I was looking for away avoiding the constant O(N) for every lookup. I can live peacefully with the O(N) for updates since they don't occur as often as reads are happening :)

@pensan 2015-11-13 15:33:41

I created a array function based on @AaronDigulla's answer. It converts the array into an object, using a given key ( Usage: myArray.toObj('id'); ) --> Array.prototype.toObj=function(r){var t,o,n=this,e={};for(t=0,o=n.length;o>t;t++)e[n[t][r]]=n[t];r‌​eturn e;};

@jbd 2016-03-07 19:04:08

This is great. As a side note, is there any significant benefit to setting the array len in the first statement of the for loop? I usually write it like this: (var x = 0; x < array.length; x++). Hadn't seen that before and curious.

@Aaron Digulla 2016-03-17 16:01:48

@jbd I have to admit that I probably copied the code from somewhere. When JavaScript was still interpreted, it was probably a small speed boost since local variables are faster than indirect references. Also, it should catch a couple of problems when you change the size of the array in the loop ... which no one ever does ;-)

@Aides 2016-06-28 15:16:53

Just to have this noted here: With this approach you convert the object to a hashmap so you have O(n) for the first lookup (since you need to convert first) and O(1) for each following one.

@Mohammad Kermani 2016-08-17 08:16:04

Thanks for your good answer, Is this a faster way? or is this way fast enough

@Simoyw 2017-02-09 13:38:13

This is the best solution as subsequent search of a specific id will require only O(1)

Related Questions

Sponsored Content

94 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6267979 View
  • 7829 Score
  • 94 Answer
  • Tags:   javascript arrays

68 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

48 Answered Questions

[SOLVED] How to check if an object is an array?

39 Answered Questions

[SOLVED] For-each over an array in JavaScript?

50 Answered Questions

20 Answered Questions

[SOLVED] Storing Objects in HTML5 localStorage

67 Answered Questions

[SOLVED] How do I correctly clone a JavaScript object?

42 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

52 Answered Questions

[SOLVED] Create GUID / UUID in JavaScript?

  • 2008-09-19 20:01:00
  • Jason Cohen
  • 1702843 View
  • 3981 Score
  • 52 Answer
  • Tags:   javascript guid uuid

39 Answered Questions

[SOLVED] How do I loop through or enumerate a JavaScript object?

Sponsored Content