JavaScript Get the index of an object by its property
Given an object, the task is to get the object's index from the array of objects of the given property name and property value using JavaScript. we're going to discuss a few techniques.
[Approach 1]: Using Array map()
The map() method creates a new array by applying a function to each element. You can then use this array to find the index.
let arrayObj = [{
prop_1: 'val',
prop_2: 'val_12',
prop_3: 'val_13'
}, {
prop_1: 'val',
prop_2: 'val_22',
prop_3: 'val_23'
}];
function findIndexInArray() {
let prop = 'prop_2';
let val = 'val_22';
console.log("Index of prop = "
+ prop + " val = " + val +
" is = " +
arrayObj.map(function (e) {
return e.prop_2;
}).indexOf(val));
}
findIndexInArray();
Output
Index of prop = prop_2 val = val_22 is = 1
Syntax:
array.map(function(currentValue, index, arr), thisValue)[Approach 2]: Using for loop
Using for loop we can iterate over the array of objects and check the given value of prop matches or not.
let arrayObj = [{
prop_1: 'val',
prop_2: 'val_12',
prop_3: 'val_13'
}, {
prop_1: 'val',
prop_2: 'val_22',
prop_3: 'val_23'
}];
function fun(array, attr, value) {
for (let i = 0; i < array.length; i += 1) {
if (array[i][attr] === value) {
return i;
}
}
return -1;
}
function print() {
let prop = 'prop_2';
let val = 'val_22';
console.log("Index of prop = '" +
prop + "' val = '" + val + "' is = "
+ fun(arrayObj, prop, val));
}
print();
Output
Index of prop = 'prop_2' val = 'val_22' is = 1
Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute in each iteration
}
[Approach 3]: Using findIndex()
The JavaScript Array.findIndex() method is used to return the first index of the element in a given array that satisfies the provided testing function (passed in by the user while calling). Otherwise, if no data is found then the value of -1 is returned.
let arrayObj = [{
prop_1: 'val',
prop_2: 'val_12',
prop_3: 'val_13'
}, {
prop_1: 'val',
prop_2: 'val_22',
prop_3: 'val_23'
}];
const index = arrayObj.findIndex(object => {
return object.prop_3 === 'val_23';
});
console.log(index);
Output
1
Syntax:
array.findIndex(callback(element, index, array), thisArg)[Approach 4]: Using some()
The JavaScript arr.some() method checks whether at least one of the elements of the array satisfies the condition checked by the argument method.
let arrayObj = [{
prop_1: 'val',
prop_2: 'val_12',
prop_3: 'val_13'
}, {
prop_1: 'val',
prop_2: 'val_22',
prop_3: 'val_23'
}];
let index;
arrayObj.some((object, idx) => {
if (object.prop_2 === 'val_12') {
index = idx;
return true;
}
});
console.log(index);
Output
0
Syntax:
array.some(callback(element, index, array), thisArg)