How can I get the index of an object by its property in JavaScript?
As the other answers suggest, looping through the array is probably the best way. But I would put it in its own function, and make it a little more abstract:
function findWithAttr(array, attr, value) {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
}
return -1;
}
var Data = [
{id_list: 2, name: 'John', token: '123123'},
{id_list: 1, name: 'Nick', token: '312312'}
];
With this, not only can you find which one contains 'John', but you can find which contains the token '312312':
findWithAttr(Data, 'name', 'John'); // returns 0
findWithAttr(Data, 'token', '312312'); // returns 1
findWithAttr(Data, 'id_list', '10'); // returns -1
The function returns -1 when not found, so it follows the same construct as Array.prototype.indexOf().
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);
Find index of object in array with specific value for specific key
You can use findIndex
method, by passing a provided callback function as argument.
let arr = [ {"type":"Grayscale","mode":"average"}, {"type":"Sepia"}, {"type":"Invert","invert":true}, {"type":"Convolute","opaque":false,"matrix":[1,1,1,1,0.7,-1,-1,-1,-1]}, {"type":"Convolute","opaque":false,"matrix":[0,-1,0,-1,5,-1,0,-1,0]}, {"type":"Brownie"}, {"type":"Brightness","brightness":0.35} ], key = 'type';console.log(arr.findIndex(elem => elem[key] == 'Invert'));
Get the index of the object inside an array, matching a condition
As of 2016, you're supposed to use Array.findIndex
(an ES2015/ES6 standard) for this:
a = [ {prop1:"abc",prop2:"qwe"}, {prop1:"bnmb",prop2:"yutu"}, {prop1:"zxvz",prop2:"qwrq"}]; index = a.findIndex(x => x.prop2 ==="yutu");
console.log(index);
Access non-numeric Object properties by index?
"I'm specifically looking to target the index, just like the first example - if it's possible."
No, it isn't possible.
The closest you can get is to get an Array of the object's keys, and use that:
var keys = Object.keys( obj );
...but there's no guarantee that the keys will be returned in the order you defined. So it could end up looking like:
keys[ 0 ]; // 'evenmore'
keys[ 1 ]; // 'something'
In an array of objects, fastest way to find the index of an object whose attributes match a search
Maybe you would like to use higher-order functions such as "map".
Assuming you want search by 'field' attribute:
var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
var objectFound = array[elementPos];
Related Topics
Access JavaScript Nested Objects Safely
How to Get the Anchor from the Url Using Jquery
Settimeout Ignores Timeout? (Fires Immediately)
How to Pass the This Context to a Function
Localstorage Access from Local File
Javascript: Getting Imagedata Without Canvas
Show a Second Dropdown Based on Previous Dropdown Selection
Using Canvas to Animate a Sorting Algorithm in Js
Jquery Duplicate Div into Another Div
Angular2/Spring Boot Allow Cross Origin on Put
How to Post with Multipart Form Data Using Fetch
Count Number of Matches of a Regex in JavaScript
Reformat String Containing Date with JavaScript