return1.at return1.at - 2 months ago 6
Javascript Question

How to find index of an object by key and value in an javascript array

Given:

var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];


Wanted:

Index of object where
attr === value
for example
attr1 === "john"
or
attr2 === "hummus"


Update:
Please, read my question carefully, i do not want to find the object via $.inArray nor i want to get the value of a specific object attribute. Please consider this for your answers. Thanks!

Answer

If you want to check on the object itself without interfering with the prototype, use hasOwnProperty():

var getIndexIfObjWithOwnAttr = function(array, attr, value) {
    for(var i = 0; i < array.length; i++) {
        if(array[i].hasOwnProperty(attr) && array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}

to also include prototype attributes, use:

var getIndexIfObjWithAttr = function(array, attr, value) {
    for(var i = 0; i < array.length; i++) {
        if(array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}
Comments