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

 

array.filter

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 ]
console.log(result);

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
}

 

jQuery.grep()

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 ]
console.log(result);

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 wouldnt 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) {
        return(names[i]);
      }
  }
};
// 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" }
console.log(search['Lee']);

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.

Worthy of Note

Worthy of Note is a site aimed at Web Designers & Developers. It offers a wide range of resources to help assist anyone in the web industry.

View