Loop Through an Object in JavaScript

This is a preview lesson
Register or sign in to take this lesson.

This tutorial show how to loop through an object using JavaScript. For this, we can use for…in or Object.entries(). Object.entries() returns array of key and value and to loop over it we can use for…of loop or forEach() method.

Example 1: Loop Through Object Using for…in Loop

// program to loop through an object using for...in loop

const car = { 
    name: 'Ford',
    engine: "2000cc",
    model: "500",
    color:"red"
};

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

Output

name - Ford
engine - 2000cc
model - 500
color - red

Example 2: Loop Through Object Using Object.entries() Method

// program to loop through an object using for...in loop

const car = { 
    name: 'Ford',
    engine: "2000cc",
    model: "500",
    color:"red"
};

// using for...of loop
for (const [key, value] of Object.entries(car)) {
    console.log(key + " - " + value );
}

//OR
// using forEach() method

Object.entries(car).forEach(([key, value]) => {
    console.log(key + " - " + value );
});

Output:

name - Ford
engine - 2000cc
model - 500
color - red

Object.entries() returns array of key and value. Object.entries(car) returns:

[ [ 'name', 'Ford' ],
  [ 'engine', '2000cc' ],
  [ 'model', '500' ],
  [ 'color', 'red' ] ]