What is the method for iterating through a JSON array to retrieve values?
You can iterate over a JSON array and retrieve values using the following method:
- Using a for loop in JavaScript:
const jsonArray = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}];
for (let i = 0; i < jsonArray.length; i++) {
console.log(jsonArray[i].name);
console.log(jsonArray[i].age);
}
- Use the forEach method in JavaScript:
const jsonArray = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}];
jsonArray.forEach(item => {
console.log(item.name);
console.log(item.age);
});
- Use the for…of loop in ES6:
const jsonArray = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}];
for (const item of jsonArray) {
console.log(item.name);
console.log(item.age);
}
These methods can be used to loop through a JSON array and extract the desired values.