How to loop through an object in JavaScript

#javascript

Last updated on Jun 5, 2021 by Suraj Sharma



In this tutorial, you will learn two ways to loop through a JavaScript object.


Iterate through an object using Object.keys


The Object.keys() method takes the object as its argument and returns an array of object's keys/properties.

const obj = {
  id: 1,
  name: 'Dan',
  state: 'CA'
};

Object.keys(obj);
// [id, name, state]

Once you get the arrayof keys you can iterate through the keys and push the key-value pairs of the JavaScript object to a new array

const obj = {
  id: 1,
  name: 'Dan',
  state: 'CA'
};

const keyValues = []

Object.keys(obj).forEach(key=>{
  keyValues.push([key, obj[key]]);
})

console.log(keyValues);
// [['id',1], ['name', 'Dan'], ['state', 'CA']];

Iterate through an object using Object.entries


The best way to iterate through a JavaScript object is to use the Object.entries() method.

The Object.entries() method takes the object as its argument and returns a multidimensional array of key-value pairs.

const obj = {
  id: 1,
  name: 'Dan',
  state: 'CA'
};

Object.entries(obj).forEach(([key, value])=> console.log(`${key}: ${value}`));
// "id: 1", "name: Dan", "state: CA"


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.