How to find index of an object by key and value in an javascript array
The Functional Approach
All the cool kids are doing functional programming (hello React users) these days so I thought I would give the functional solution. In my view it's actually a lot nicer than the imperatival for
and each
loops that have been proposed thus far and with ES6 syntax it is quite elegant.
Update
There's now a great way of doing this called findIndex
which takes a function that return true
/false
based on whether the array element matches (as always, check for browser compatibility though).
var index = peoples.findIndex(function(person) {
return person.attr1 == "john"
});
With ES6 syntax you get to write this:
var index = peoples.findIndex(p => p.attr1 == "john");
The (Old) Functional Approach
TL;DR
If you're looking for index
where peoples[index].attr1 == "john"
use:
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
Explanation
Step 1
Use .map()
to get an array of values given a particular key:
var values = object_array.map(function(o) { return o.your_key; });
The line above takes you from here:
var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];
To here:
var values = [ "bob", "john", "larry" ];
Step 2
Now we just use .indexOf()
to find the index of the key we want (which is, of course, also the index of the object we're looking for):
var index = values.indexOf(your_value);
Solution
We combine all of the above:
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
Or, if you prefer ES6 syntax:
var index = peoples.map((o) => o.attr1).indexOf("john");
Demo:
var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
console.log("index of 'john': " + index);
var index = peoples.map((o) => o.attr1).indexOf("larry");
console.log("index of 'larry': " + index);
var index = peoples.map(function(o) { return o.attr1; }).indexOf("fred");
console.log("index of 'fred': " + index);
var index = peoples.map((o) => o.attr2).indexOf("pizza");
console.log("index of 'pizza' in 'attr2': " + index);
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;
}