DEV Community

Cover image for Unlocking the Power of Array and Object Iteration in JavaScript: A Beginner's Guide with Easy-to-Follow Examples
Shaikh AJ
Shaikh AJ

Posted on

Unlocking the Power of Array and Object Iteration in JavaScript: A Beginner's Guide with Easy-to-Follow Examples

Introduction:

In JavaScript, arrays and objects are fundamental data structures used to store and organize data. When working with these data structures, it's common to iterate over their elements to perform various operations. In this post, we will explore how to loop over an array of objects and objects themselves in JavaScript. We'll cover different loop constructs and provide multiple examples to demonstrate their usage. Let's dive in!

1. Looping Over an Array of Objects:

Example 1: Using a for loop

   const students = [
     { name: 'Alice', age: 20 },
     { name: 'Bob', age: 22 },
     { name: 'Charlie', age: 21 }
   ];

   for (let i = 0; i < students.length; i++) {
     console.log(students[i].name);
   }
Enter fullscreen mode Exit fullscreen mode

Output:

   Alice
   Bob
   Charlie
Enter fullscreen mode Exit fullscreen mode

** Example 2: Utilizing the forEach method**

   students.forEach((student) => {
     console.log(student.name);
   });
Enter fullscreen mode Exit fullscreen mode

Output:

   Alice
   Bob
   Charlie
Enter fullscreen mode Exit fullscreen mode

Example 3: Employing the for...of loop

   for (const student of students) {
     console.log(student.name);
   }
Enter fullscreen mode Exit fullscreen mode

Output:

   Alice
   Bob
   Charlie
Enter fullscreen mode Exit fullscreen mode

Example 4: Using the map method for transformation

   const studentNames = students.map((student) => student.name);
   console.log(studentNames);
Enter fullscreen mode Exit fullscreen mode

Output:

   ['Alice', 'Bob', 'Charlie']
Enter fullscreen mode Exit fullscreen mode

2. Accessing Object Properties in a Loop

:

Example 1: Looping over object keys with for...in loop

   const student = { name: 'Alice', age: 20 };

   for (const key in student) {
     console.log(key, student[key]);
   }
Enter fullscreen mode Exit fullscreen mode

Output:

   name Alice
   age 20
Enter fullscreen mode Exit fullscreen mode

Example 2: Using Object.entries to iterate over key-value pairs

   Object.entries(student).forEach(([key, value]) => {
     console.log(key, value);
   });
Enter fullscreen mode Exit fullscreen mode

Output:

   name Alice
   age 20
Enter fullscreen mode Exit fullscreen mode

** Example 3: Utilizing Object.values to loop over property values**

   Object.values(student).forEach((value) => {
     console.log(value);
   });
Enter fullscreen mode Exit fullscreen mode

Output:

   Alice
   20
Enter fullscreen mode Exit fullscreen mode

Example 4: Combining Object.keys and forEach for specific property manipulation

   Object.keys(student).forEach((key) => {
     if (key === 'name') {
       student[key] = student[key].toUpperCase();
     }
   });

   console.log(student);
Enter fullscreen mode Exit fullscreen mode

Output:

   { name: 'ALICE', age: 20 }
Enter fullscreen mode Exit fullscreen mode

3. Nesting Loops for Nested Arrays and Objects:

Example 1: Looping over an array of objects with nested arrays

   const data = [
     { name: 'Alice', courses: ['Math', 'Science'] },
     { name: 'Bob', courses: ['History', 'English'] }
   ];

   for (const item of data) {
     console.log(item.name);

     for (const course of item.courses) {
       console.log('- ', course);
     }


 }
Enter fullscreen mode Exit fullscreen mode

Output:

   Alice
   -  Math
   -  Science
   Bob
   -  History
   -  English
Enter fullscreen mode Exit fullscreen mode

Example 2: Iterating through nested objects within an array

   const data = [
     { name: 'Alice', info: { age: 20, city: 'New York' } },
     { name: 'Bob', info: { age: 22, city: 'Los Angeles' } }
   ];

   for (const item of data) {
     console.log(item.name);
     console.log('Age:', item.info.age);
     console.log('City:', item.info.city);
   }
Enter fullscreen mode Exit fullscreen mode

Output:

   Alice
   Age: 20
   City: New York
   Bob
   Age: 22
   City: Los Angeles
Enter fullscreen mode Exit fullscreen mode

Example 3: Nesting loops for multi-dimensional arrays

   const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

   for (const row of matrix) {
     for (const num of row) {
       console.log(num);
     }
   }
Enter fullscreen mode Exit fullscreen mode

Output:

   1
   2
   3
   4
   5
   6
   7
   8
   9
Enter fullscreen mode Exit fullscreen mode

4. Common Operations during Object and Array Loops:

Example 1: Filtering an array of objects based on a condition

   const students = [
     { name: 'Alice', age: 20 },
     { name: 'Bob', age: 22 },
     { name: 'Charlie', age: 21 }
   ];

   const adults = students.filter((student) => student.age >= 21);
   console.log(adults);
Enter fullscreen mode Exit fullscreen mode

Output:

   [
     { name: 'Bob', age: 22 },
     { name: 'Charlie', age: 21 }
   ]
Enter fullscreen mode Exit fullscreen mode

Example 2: Modifying object properties using loops

   for (const student of students) {
     student.age += 1;
   }

   console.log(students);
Enter fullscreen mode Exit fullscreen mode

Output:

   [
     { name: 'Alice', age: 21 },
     { name: 'Bob', age: 23 },
     { name: 'Charlie', age: 22 }
   ]
Enter fullscreen mode Exit fullscreen mode

Example 3: Calculating aggregate values from an array of objects

   const totalAge = students.reduce((sum, student) => sum + student.age, 0);
   console.log(totalAge);
Enter fullscreen mode Exit fullscreen mode

Output:

   66
Enter fullscreen mode Exit fullscreen mode

Example 4: Searching for a specific object or property within an array

   const foundStudent = students.find((student) => student.name === 'Bob');
   console.log(foundStudent);
Enter fullscreen mode Exit fullscreen mode

Output:

   { name: 'Bob', age: 22 }
Enter fullscreen mode Exit fullscreen mode

Conclusion:

Looping over arrays of objects and objects themselves is a fundamental skill in JavaScript. By mastering the various loop constructs and techniques provided in this post, you can effectively iterate through your data, perform operations, and manipulate the values to meet your requirements. Remember to choose the appropriate loop construct based on the specific task at hand and consider performance optimizations when dealing with large datasets. With practice and experience, you'll become proficient in handling complex data structures in JavaScript.

Happy coding!

Top comments (0)