jQuery - Search object array for a key value match
Using jQuery's $.each to search an object array for a key value match
HTML
<span id="output"></span>
JavaScript
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;
var self = this;
for(var index=0; index < self.length; index++){
var item = self[index];
if (item.hasOwnProperty(property)) {
if (item[property].toLowerCase() === searchFor.toLowerCase()) {
retVal = index;
return retVal;
}
}
};
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");
var j = people.inArray("XYZ987", "code");
$('#output').text(people[i].name + ' - ' + people[j].name);
// or we could create a function on the Array prototype directly
/*
Array.prototype.inArray2 = 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;
};
*/