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);
Get the index of the array when array object matching condition
You need recursion
const findItemNested = (arr, level, nestingKey) => (
arr.reduce((a, item, index) => {
if (a) return a;
if (item.level === level) return index;
if (item[nestingKey]) return findItemNested(item[nestingKey], level, nestingKey)
}, null)
);
const testArr = [
{
'id':'id_1',
'level':'1-1',
'children':[
{'id':'id_1'},
{'level':'1-1-0'},
{'children':[]}
]
},
{'id':'id_2','level':'2-2','children':[{'id':'id_1'},{'level':'2-1-0'},{'children':[]}]}
];
const res = findItemNested(testArr, '2-1-0', "children");
console.log(res) // 1
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().
Find all index based on condition
The
findIndex
method returns the index of the first element in the
array that satisfies the provided testing function. Otherwise, it
returns -1, indicating that no element passed the test. - MDN
You can use reduce
here:
const a = [
{ prop1: "abc", prop2: "yutu" },
{ prop1: "bnmb", prop2: "yutu" },
{ prop1: "zxvz", prop2: "qwrq" },
];
const result = a.reduce((acc, curr, i) => {
if (curr.prop2 === "yutu") acc.push(i);
return acc;
}, []);
console.log(result);
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];
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);
Get index of Object inside Array and use it in a function
Do it in two steps. First create the array of objects, then fill in the comments
property by calling the function on each element.
const foo = [
{
id: 1,
},
{
id: 34,
},
{
id: 21,
}
]
foo.forEach(el => el.comments = getComments(el));
function getComments(obj) {
return obj.id;
}
console.log(foo);
Find index of javascript array of objects based on object field value
You'd have to iterate, here's a very simple example
var index = null;
for (var i=0; i<array.length; i++) {
if ( array[i].id == 15 ) {
index = i;
break;
}
}
That gets you the index, if you just want to return the object you can do
var obj = array.filter(function(obj) {
return obj.id == 15;
}).shift();
Related Topics
What Is the Correct Term for Variable Shadowing in JavaScript
Recursive Matching with Regular Expressions in JavaScript
How to Loop Through All Dom Elements on a Page
How to Remove All the Options of a Select Box and Then Add One Option and Select It with Jquery
Adding Console.Log to Every Function Automatically
How to Escape JavaScript in Jsp
How to Duplicate Object Properties in Another Object
Relation Between Commonjs, Amd and Requirejs
How to Offset the Center Point in Google Maps API V3
How to Map More Than One Property from an Array of Objects
How to Use Redirect in Version 5 of React-Router-Dom of Reactjs
Optional Chaining in JavaScript
How to Overload Functions in JavaScript
Difference Between JSON.Stringify and JSON.Parse
How to Link Each User to Their Data in Firebase
How to Replace Remapcolums with Remapcolumnsbyname in Free Jqgrid