Different Ways to iterate through Objects and Arrays in JavaScript

Looping through an Object or Array is most common task that we can see in our project. Let’s discuss different ways to do so.

Looping through Objects

Using Object.keys()

To loop through all the keys of object, you can use Object.keys() with map() method.

const car = {
    brand: 'Mercedes',
    model: 'Benz',
    color: 'Black'
}

Object.keys(car).map((key) => {
    console.log(key + '-' + car[key]);
});

/*
  brand-Mercedes
  model-Benz
  color-Black
*/

Using Object.entries()

Object.entries(car).map((entry) => {
    console.log(entry[0] + '-' + entry[1]);
});

/*
  brand-Mercedes
  model-Benz
  color-Black
*/

The for…in Loop

for(let key in car) {
    console.log(key + '-' + car[key]);
}

/*
brand-Mercedes
model-Benz
color-Black
*/

Looping through Arrays

Using for Loop

const cars = ['BMW', 'Audi', 'Mercedes'];

for (let i = 0; i < cars.length; i++) {
    console.log(cars[i]);
}

/*
BMW
Audi
Mercedes
*/

Using for…of Loop

for(let car of cars) {
    console.log(car);
}

/*
BMW
Audi
Mercedes
*/

Using forEach() method

cars.forEach(car => console.log(car));

/*
BMW
Audi
Mercedes
*/

Using Array.map()

cars.map(car => {
    console.log(car);
});

/*
  BMW
  Audi
  Mercedes
*/

Using Array.filter()

The filter() method finds and filters out elements that do not pass the condition. This method takes a function as argument which returns true or false. This function executes for each element in array. If the function returns true for any element then only that element gets included in the returned array.

const numbers = [5, 8, 20, 35, 10, 4];

const divisibleByTwoNumbers = numbers.filter((value, index, array) => {
    return (value %% 2) == 0;
});

console.log(divisibleByTwoNumbers); // [8, 20, 10, 4]

Using Array.reduce():

The reduce() method loops through each element and returns a single value.

const numbers = [5, 8, 20, 35, 10, 4];

const sum = numbers.reduce((total, value) => {
    return total + value;
});

console.log(sum); // 82

Reference

One thought on “Different Ways to iterate through Objects and Arrays in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *