Iterating and printing a JSON with no initial key and multiple entries?

When working with JSON arrays containing multiple objects, you can iterate through each entry using JavaScript's forEach() method. This is particularly useful when your JSON data doesn't have a single root key and contains multiple entries.

Syntax

array.forEach((element, index) => {
    // Process each element
});

Example: Iterating Through Student Records

const details = [
    {
        "studentId": 101,
        "studentName": "John Doe"
    },
    {
        "studentId": 102,
        "studentName": "David Miller"
    }
];

details.forEach(obj => {
    console.log("StudentId=" + obj.studentId);
    console.log("StudentName=" + obj.studentName);
    console.log("---");
});
StudentId=101
StudentName=John Doe
---
StudentId=102
StudentName=David Miller
---

Alternative Methods

Using for...of Loop

const products = [
    { "id": 1, "name": "Laptop", "price": 999 },
    { "id": 2, "name": "Phone", "price": 599 }
];

for (const product of products) {
    console.log(`Product: ${product.name}, Price: $${product.price}`);
}
Product: Laptop, Price: $999
Product: Phone, Price: $599

Using map() for Transformation

const users = [
    { "name": "Alice", "age": 25 },
    { "name": "Bob", "age": 30 }
];

const userSummaries = users.map(user => `${user.name} (${user.age} years old)`);
console.log(userSummaries);
[ 'Alice (25 years old)', 'Bob (30 years old)' ]

Comparison of Methods

Method Use Case Returns Value
forEach() Simple iteration and processing undefined
for...of Clean iteration syntax N/A (loop construct)
map() Transform data into new array New array

Conclusion

Use forEach() for simple iteration through JSON arrays without initial keys. For data transformation, prefer map(), and for cleaner syntax, consider for...of loops.

Updated on: 2026-03-15T23:18:59+05:30

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements