DEV Community

Shuvo
Shuvo

Posted on

5 2

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 🚀

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs