Javascript/JSON: Find Index in an Array of Objects

JSON is one of my favorite data models notation (xml = :(). A lot of times, I get arrays of objects (hash tables) that I then have to search again an again to find the index of the object inside that array. Here’s a quick function to find it:


/*
function findIndexByKeyValue: finds "key" key inside "ob" object that equals "value" value
example: findIndexByKeyValue(students, 'name', "Jim");
object: students = [
   {name: 'John', age: 100, profession: 'Programmer'},
   {name: 'Jim', age: 50, profession: 'Carpenter'}
];
would find the index of "Jim" and return 1
*/

function findIndexByKeyValue(obj, key, value)
{
	for (var i = 0; i < obj.length; i++) {
		if (obj[i][key] == value) {
			return i;
		}
	}
	return null;
}

Leave a Reply

Your email address will not be published. Required fields are marked *