Wednesday, January 29, 2014

Find object by id in array of javascript objects

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},etc.]

var result = $.grep(myArray, function(e){ return e.id == id; });
 
if (result.length == 0) {
  // not found
} else if (result.length == 1) {
  // access the foo property using result[0].foo
} else {
  // multiple items found
}
 
Source - stackoverflow.com