DEV Community

Shuvo
Shuvo

Posted on

How To Loop Over An Object In Javascript

1. Use Object.keys to get an array of keys of the object and loop over it.

let myObj = {
  name: 'Shuvo',
  tech: 'javascript',
  hobby: 'learning javascript',
  favFood: 'beef steak!',
};

// way: 1
 Object.keys(myObj).map((key) => {
   console.log(`key: ${key} value: ${myObj[key]}`);
 });


// output

// key: name value: Shuvo

// key: tech value: javascript

// key: hobby value: learning javascript

// key: favFood value: beef steak!


Enter fullscreen mode Exit fullscreen mode

2. Use For...in Loop to over the object.

// way: 2
for (key in myObj) {
  console.log(`key: ${key} value: ${myObj[key]}`);
}

// output

// key: name value: Shuvo

// key: tech value: javascript

// key: hobby value: learning javascript

// key: favFood value: beef steak!
Enter fullscreen mode Exit fullscreen mode

3. Use Object.values() method. In this time you will get all the value of the remaining keys.

// way: 3 

Object.values(myObj).forEach((value) => {
  console.log('value: ', value);
});

// output
// value: Shuvo

// value: javascript

// value: learning javascript

// value: beef steak!
Enter fullscreen mode Exit fullscreen mode

4. Use Object.entries() method. It will return array of key and value



// way: 4 

Object.entries(myObj).forEach((arr) => {
  console.log('arr: ', arr);
});

// output
// arr: ["name", "Shuvo"]

// arr: ["tech", "javascript"]

// arr: ["hobby", "learning javascript"]

// arr: ["favFood", "beef steak!"]
Enter fullscreen mode Exit fullscreen mode

And that's it.Play with it more 🚀

Top comments (0)