forEach object JavaScript | Example code

  • by

JavaScript forEach() function lets you iterate over an array, but not over an object. If you want iterate over a JavaScript object using forEach() then first convert object into an array, using Object.keys(), Object.values(), or Object.entries().

Under ECMAScript 5, you can combine Object.keys() and Array.prototype.forEach():

var obj = {
  first: "John",
  last: "Doe"
};


Object.keys(obj).forEach(function(key) {
  console.log(key, obj[key]);
});

Example forEach object JavaScript

Simple example code iterate over each key in the object using forEach() with Object.keys() function.

<!DOCTYPE html>
<html>
<body>

  <script>

    const obj = {
      name: 'James Bond',
      rank: '007'
    };

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

  </script>

</body>
</html> 

Output:

forEach object JavaScript

Using Object.values()

Object.values(obj).forEach(val => {
  console.log(val);
});

Using Object.entries()

Object.entries(obj).forEach(entry => {
  const [key, value] = entry;
  console.log(key, value);
});

Do comment if you have any doubts or suggestions on this JS object topic,

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.