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
Release: 2024-11-27 20:28:14
Original
555 people have browsed it

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" }]
Copy after login

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"}
];
Copy after login
  1. Use a For Loop to Iterate Over the Array:
for (var i = 0; i < arr.length; i++) {
Copy after login
  1. Access the Current Object within the Loop:
var obj = arr[i];
Copy after login
  1. Use Another For Loop to Iterate Over the Object's Properties:
for (var key in obj) {
Copy after login
  1. Extract and Display the Property Values:
var value = obj[key];
document.write("<br><br>array index: " + i);
document.write("<br> - " + key + ": " + value);
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template