Skip to content

JavaScript loop through JSON object

  • by

You can use a for...in loop to loop through JSON objects in JavaScript. It will iterate over the keys of the object and access their corresponding values.

Note: that the order in which the keys are iterated over is not guaranteed.

JavaScript loop through JSON object example

Simple example code for…in loop iterates over all enumerable properties of an object: Inside the loop, we use template literals to print the key-value pairs to the console.

<!DOCTYPE html>
<html>

<body>
  <script >
    const data = {
      "name": "John",
      "age": 30,
      "city": "New York"
    };

    for (let key in data) {
      console.log(`${key}: ${data[key]}`);
    }

  </script>
</body>
</html>

Output:

JavaScript loop through JSON object

Looping through JSON object nested properties and displaying them if not null

Using Object.entries() and some Array prototype methods to filter out nulls and properly stringify the result.

var obj = JSON.parse('{"alias":"AS","id":"4a4e1584-b0a7-4069-8851-0ee7f9e18267","name":"asdfadf","properties":{"shape":null,"units":"gms","dimension":null,"maxWeight":"sdf","minWeight":"asfd"}}');

function getPropertyString(obj) {
  return Object.entries(obj)
  .filter(el => el[1] != null)
  .map(el => el.join(': '))
  .join(', ');
}
  
console.log(getPropertyString(obj.properties));

Step by step:

  1. Object.entries(obj) – Returns an array of arrays, structured as:
    [[key1, value1], [key2, value2], ... , [keyN, valueN]]
  2. Array.prototype.filter(func) – Returns a copy of the array with all elements that return true from the provided callback
    • In this case, filters out all arrays from entries that have a null value
  3. Array.prototype.map(func) – Returns a copy of the array after transforming each element with the provided callback
    • In this case, transforms all [key, value] arrays to be a string with the format "key: value"
  4. Array.prototype.join(str) – Returns a string representing the array with each element joined by the provided string
    • Joins the "key: value" strings to each other with ", " in between

Do comment if you have any doubts or suggestions so this Js JSON object.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading