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.