Iterate JSON map in JavaScript | Example code

  • by

Use a “for … in” loop to Iterate JSON map in JavaScript. However, you also have to make sure that the key you get is an actual property of an object, and doesn’t come from the prototype.

Iterate JSON map in JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    var p = {
      "p1": "value1",
      "p2": "value2",
      "p3": "value3"
    };

    for (var key in p) {
      if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
      }
    }

  </script>

</body>
</html> 

Output:

Iterate JSON map in JavaScript

For-of with Object.keys() alternative:

var p = {
    0: "value1",
    "b": "value2",
    key: "value3"
};

for (var key of Object.keys(p)) {
    console.log(key + " -> " + p[key])
}

Using the new Object.entries() method:

Note: This method is not supported natively by Internet Explorer. You may consider using a Polyfill for older browsers.

const p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (let [key, value] of Object.entries(p)) {
  console.log(`${key}: ${value}`);
}

Source: stackoverflow.com/

Do comment if you have any doubts or suggestions on this JS JSON topic.

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

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published.

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