This guide will explain how to iterate a loop through a JSON array using JavaScript.
How to Iterate a Loop through a JSON Array Using JavaScript?
The “JSON array” values can be accessed via a loop. In-looping the JSON (JavaScript Object Notation) is considered the best technique to transport data in an array format. This is because it is a light format to store and transfer the required data from one place to another.
This section uses the commonly used “for” loop to iterate a JSON array using JavaScript.
Syntax (JSON Array)
Here, “value1”, “value2”, and “valueN” refer to the values that need to be iterated.
Let’s perform the looping through a “JSON” array in JavaScript practically.
HTML Code
Let’s have a look at the following HTML code:
In the above lines of code:
- The “<h2> tag defines a subheading.
- The “<p>” tag creates a paragraph statement.
- Lastly, the “<p>” tag defines an empty paragraph having an id “sample” to display the JSON array values.
JavaScript Code
Next, move on to the below-provided code:
const JSONarray = '{"name":"Johnson", "age":35, "cars":["BMW", "Honda", "Corolla"]}';
const Obj = JSON.parse(JSONarray);
let text = "";
for (let k = 0; k < Obj.cars.length; k++) {
text += Obj.cars[k] + ", ";
}
document.getElementById("sample").innerHTML = text;
</script>
In this code block:
- Define a JSON array named “JSONarray” with a “const” keyword having an ordered list of values.
- The “Obj” object utilizes the “parse()” method that converts the specified JSON array text into the JavaScript object.
- After that, the “text” variable stores an empty value.
- Next, apply a “for” loop to iterate over the properties of “Obj” concatenated with the included JSON array against the key “car”.
- Also, associate the “length” property and increment the loop to carry out the iteration appropriately.
- Lastly, apply the “getElementById()” method to access the added empty paragraph using its id “sample”. It will display the JSON array values through the “innerHTML” property.
Output
The output shows all the values of the added JSON array using the “for” loop.
Conclusion
“JSON arrays” can be easily iterated using JavaScript with the help of the “for” loop. This is a common process and is generally used in web development to retrieve the data in JSON format from the database or the API. This guide has explained a brief description to iterate a loop through a JSON array using JavaScript.