JavaScript loop through object (keys and values)


const obj1 = {

  a: 'str',

  b: 55,

  c: true

};

 

// version 1

Object.entries(obj1).forEach(([key, value]) => {

  console.log(`${key}: ${value}`);

});



// version 2

Object.keys(obj1).forEach((key) => {

  console.log(`${key}: ${obj1[key]}`);

});

 

// version 3

for (const [key, value] of Object.entries(obj1)) {

  console.log(`${key}: ${value}`);

}

 

// version 4

for (const prop in obj1) {

  console.log(`${prop}: ${obj1[prop]}`);

}

 

// expected output for all versions:

// "a: str"

// "b: 55"

// "c: true"

Leave a Comment