Skip to content

foreach JSON Object JavaScript

  • by

In JavaScript, you can use a loop like forEach to iterate over an array of JSON objects. Each JSON object can be accessed within the loop, allowing you to perform operations or access specific properties.

foreach JSON Object JavaScript example

Simple example code.

const jsonArray = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'Bob', age: 35 }
];

jsonArray.forEach((jsonObject) => {
  // Accessing properties of each JSON object
  const name = jsonObject.name;
  const age = jsonObject.age;

  // Performing operations with the properties
  console.log(`Name: ${name}, Age: ${age}`);
});

Output:

foreach JSON Object JavaScript

JavaScript JSON foreach

In JavaScript, the term “JSON” refers to the JavaScript Object Notation, which is a data format used to represent structured data. It’s important to note that JSON itself does not have a forEach method. However, you can still iterate over the properties of a JSON object using a for...in loop or by accessing the object’s keys.

Here’s an example of using a for...in loop to iterate over the properties of a JSON object:

const jsonObject = {
  name: 'John',
  age: 25,
  city: 'New York'
};

for (let key in jsonObject) {
  if (jsonObject.hasOwnProperty(key)) {
    const value = jsonObject[key];
    console.log(`${key}: ${value}`);
  }
}

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. Required fields are marked *