I often have the need to search a javascript array that contains objects. I want to search for an object in the array that has a property match. For example, searching an array of Person objects for where the person's id/key === "ABC123"
It can be done pretty easily using jQuery using the $.each method, which is what I settled on. You can see the example here in jsFiddle. http://jsfiddle.net/johnpapa/EJAFG/
I'm wondering if anyone else has found a faster and/or better way to do this?
var Person = function(code, name) {
this.code = code;
this.name = name;
};
var people = [
new Person("ABC123", "Tooth Fairy"),
new Person("DEF456", "Santa Claus"),
new Person("PIR000", "Jack Sparrow"),
new Person("XYZ987", "Easter Bunny")
];
var utils = {};
// Could create a utility function to do this
utils.inArray = function(searchFor, property) {
var retVal = -1;
$.each(this, function(index, item) {
if (item.hasOwnProperty(property)) {
if (item[property].toLowerCase() === searchFor.toLowerCase()) {
retVal = index;
return false;
}
}
});
return retVal;
};
// or we could create a function on the Array prototype indirectly
Array.prototype.inArray = utils.inArray;
// let's use the prototype for now
var i = people.inArray("PIR000", "code");
$('#output').text(people[i].name);
There are lot's of questions similar to this one, but I have yet to see one with a solution other than iterating (like I did here).
So the question is ... is there a better way?