Home >Web Front-end >JS Tutorial >How to Iterate Through a JSON Array in JavaScript?

How to Iterate Through a JSON Array in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-27 20:28:14495browse

How to Iterate Through a JSON Array in JavaScript?

Iterating Through a JSON Structure in JavaScript

This article offers a practical solution to iterating over a JSON structure in JavaScript, addressing the specific question:

Question:

How do I iterate over the following JSON structure in JavaScript?

[{ "id": "10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]

Answer:

The provided JSON structure is in an array format. To iterate over it, follow these steps:

  1. Create an Array Object:
var arr = [
    {"id":"10", "class": "child-of-9"},
    {"id":"11", "class": "child-of-10"}
];
  1. Use a For Loop to Iterate Over the Array:
for (var i = 0; i < arr.length; i++) {
  1. Access the Current Object within the Loop:
var obj = arr[i];
  1. Use Another For Loop to Iterate Over the Object's Properties:
for (var key in obj) {
  1. Extract and Display the Property Values:
var value = obj[key];
document.write("<br><br>array index: " + i);
document.write("<br> - " + key + ": " + value);

This code snippet will iterate over each object in the JSON array and display its properties and values in the document.

The above is the detailed content of How to Iterate Through a JSON Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn