Iterate over JSON object in JavaScript | Example code

  • by

First, convert the data into a JSON object using the JSON parse() method. Then Iterate over JSON objects using for-each in JavaScript.

Iterate over JSON object in JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    var data = '{"employees":\n\
    [{"101" : {"fName":"John", "lName":"Doe"}},\n\
    {"102" : {"fName":"Anna", "lName":"Smith"}},\n\
    { "103" : {"fName":"Peter", "lName":"Jones"}}]}';  


    var empObj = JSON.parse(data);

    empObj.employees.forEach((item) => {
      Object.entries(item).forEach(([key, val]) => {
        console.log(`key-${key}-val-${JSON.stringify(val)}`)
      });
    });
  </script>

</body>
</html> 

Output:

Iterate over JSON object in JavaScript

Loop through json object JavaScript

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

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

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

Leave a Reply

Your email address will not be published.

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