Jump to navigation

Search for object in array

You might have an array containing multiple objects and you need to access. How do you do it?

var names = [
  {'id': 1, 'fname':'Jordan', 'lname':'Lane'},
  {'id': 2, 'fname':'Lee', 'lname':'Torston'},
  {'id': 3, 'fname':'Shane', 'lname':'Prendergast'},
  {'id': 4, 'fname':'Shane', 'lname':'Tsagrednerp'}

It's important to say that some techniques will be better - and faster - than others, depending on what you want to achieve. However here are some examples....


This makes use of ES5 array.filter method, however this is a relatively new function so check browser support. You can find more array methods here if you're interested.

var result = names.filter(function(obj) {
  return obj.fname === 'Shane';

// Array [ Object, Object ]

As we can see in the example there may be more than two results, so we would need some additional code to deal with that..

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


This one makes use of the grep() function in jQuery. The purpose of this function is to  "finds the elements of an array which satisfy a filter function. The original array is not affected". The following returns a new array with results. As with the above example,  you would need to check if there was more than one result.

Apparently grep is up to 3 times faster than using array.filter, you can read more about that on this Stack Overflow.

var result = $.grep(names, function(e){ return e.fname === 'Jordan'; });
// Array [ Object ]

Example from Guffa on Stack Overflow.

Vanilla JS

A function which makes use of a 'for' loop and returns the first object it encounters. This function wouldn't be suitable if there were multiple instances in the array. You could re-factor the function to create an array of the results but this would effectively be doing what the previous two examples do.

var findProperty = function(prop, val) {
  for (var i = 0; i < names.length; i++) {
      if(names[i][prop] == val) {
// Object { id: 1, fname: "Jordan", lname: "Lane" }
console.log(findProperty('lname', 'Lane'));

Lookup Object

The final one is smart from Aaron Digulla as it creates a new object based on your requirements and is well suited if you need to do many lookups, as it doesn't need to loop through an array each time. However this shouldn't be used if you are only looking for something once, or rely on the order of the properties. It should also be noted it will only return one object.

var lookup = {};

for (var i = 0; i < names.length; i++) {
    lookup[names[i].fname] = names[i];

// Object { id: 2, fname: "Lee", lname: "Torston" }

There are also various other libraries such as Underscore.js which can help out but I would always use native methods where possible, unless I needed extra functionality or a helping hand for whatever reason.