Use the JavaScript Array findIndex() method to find an index of an object in an array. Function calls are expensive, therefore with really big arrays a simple loop will perform much better than findIndex
:
JavaScript finds the index of the object in an array
Simple example code. The findIndex()
method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1
is returned.
<!DOCTYPE html>
<html>
<body>
<script>
arr = [
{prop1:"abc",prop2:"qwe"},
{prop1:"bnmb",prop2:"yutu"},
{prop1:"zxvz",prop2:"qwrq"}];
index = arr.findIndex(x => x.prop2 ==="yutu");
console.log(index);
</script>
</body>
</html>
Output:
You need to check one of the properties of the objects of the array. Then return the result of the check.
var array = [{ one: 1, two: 2 }, { one: 3, two: 4 }],
result = array.findIndex(function(object) {
return object.two === 2;
});
console.log(result);
Find the index of javascript “Array of objects” based on the object field value
You’d have to iterate, here’s a very simple example.
var arr = [{id:1, saved:0, name: "name1"}, {id:26, saved:0, name: "name2"},
{id:3, saved:0, name: "name3"}, {id:15, saved:0, name: "name4"}];
var index = null;
for (var i=0; i<arr.length; i++) {
if ( arr[i].id == 15 ) {
index = i;
break;
}
}
console.log(index)
Output: 3
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();
Do comment if you have any doubts or suggestions on this JS object array topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version