How to use for loop In Javascript

Using for loop we can iterate over the array of objects and check the given value of prop matches or not.

Example 1: This example searches for the attribute name and its value in the array and if it gets it, It returns the index of an object otherwise returns -1.

Javascript




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_2(array, attr, value) {
    for (let i = 0; i < array.length; i += 1) {
        if (array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}
 
function GFG_Fun() {
    let prop = 'prop_2';
    let val = 'val_22';
 
    console.log("Index of prop = '" +
        prop + "' val = '" + val + "' is = "
        + fun_2(arrayObj, prop, val));
}
 
GFG_Fun();


Output

Index of prop = 'prop_2' val = 'val_22' is = 1

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.

Below are the following approaches:

Table of Content

  • Using Array map() Method
  • Using for loop
  • Using findIndex() Method
  • Using some() Method

Similar Reads

Method 1: Using Array map() Method

This method creates a new array with the return value of calling a function for every array element. This method calls the provided function once for each element in an array, with maintaining the order....

Method 2: Using for loop

...

Method 3: Using findIndex() Method

Using for loop we can iterate over the array of objects and check the given value of prop matches or not....

Method 4: Using some() Method

...

Contact Us