How to loop through object array in JavaScript in the best way?

Many times during application development, we need to loop through an object array that has multiple attributes.

What are Object Arrays?

Object arrays are complex array structures that are often difficult to manipulate than simple arrays.

An array of objects can store multiple values in a single array variable. The object may contain anything in the real world such as person names, subjects, and customers list, and so. Objects are easier to use in some situations if you know well how to process the data within. The character set inside objects is known as the object property. We can refer to a property of an object using the dot notation and [] notation.

We can also search for specific conditions for the properties. Object arrays are often in the format: [{},{},{}]. Here each curly braces hold multiple properties. Let us learn of best ways to read data from an object array.

Consider the code sample below of an array of objects. Here an object refers to a student, that can have multiple properties, for example, name, age, grades etc.

    // Array of student objects
    var students_list= {
        {
            name: 'mary',
            age: 12,
            gender: 'female',
            grade: B

        },
        {
             name: 'alex',
             age: 14,
             gender: 'male',
             grade: B
        },
        {
             name: 'rita',
             age: 13,
             gender: 'female',
             grade: A
        },
        {
             name: 'harry',
             age: 12,
             gender: 'male',
             grade: C
        }
    };

Suppose you need to read data for a specific student, so you should refer to the object and its property as shown below.

  console.log('Rita's gender' + students_list.rita.gender); // using dot notation
  console.log('Rita's gender' + students_list.rita[gender]); // using [] notation

Loop through Object Array

Sometimes we may need to loop through the entire array of objects and look for specific values. This helps reading specific records of an array. For example, we need a list of all female students or the students who scored an A. We can loop through the array object using forEach and simply pass out search criteria using the dot notation, as shown below.

students_list.forEach((student) => {
        if(student.gender === "female"){
            console.log("list female students", student);
            // we can also push female students to a separate array list
            female_student.push(student);
        }
    });

There are many differences between array and array of objects. However, array methods can be applied to even an object arrays. As shown above, after looping through your array, you can use your results in any way. The example above shows, you can also push your results into a new array, that is only for female students.