Parsing array of objects inside an object using maps or forEach using JavaScript?

When working with nested data structures in JavaScript, you often need to parse arrays of objects within objects. This can be efficiently done using map() or forEach() methods to iterate through the data and extract the information you need.

Understanding the Data Structure

Consider a JSON object containing store data with nested arrays of items:

let json = {
    storeData: [
        {
            items: [
                {
                    itemID: 12,
                    cost: {
                        costNum: 100,
                    },
                },
                {
                    itemID: 22,
                    cost: {
                        costNum: 250,
                    },
                },
                {
                    itemID: 19,
                    cost: {
                        costNum: 350,
                    },
                },
            ],
        },
    ],
};

Using forEach() Method

The forEach() method is ideal for iterating through arrays when you want to perform actions without creating a new array:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Parse Array of Objects</title>
    <style>
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
        }
        .result {
            font-size: 18px;
            font-weight: 500;
            color: rebeccapurple;
            margin: 20px 0;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <h1>Parse Array of Objects Inside Object</h1>
    <div class="result"></div>
    <button class="Btn">Parse with forEach</button>
    <button class="MapBtn">Parse with map</button>
    <button class="ClearBtn">Clear Results</button>
    
    <script>
        let json = {
            storeData: [
                {
                    items: [
                        {
                            itemID: 12,
                            cost: {
                                costNum: 100,
                            },
                        },
                        {
                            itemID: 22,
                            cost: {
                                costNum: 250,
                            },
                        },
                        {
                            itemID: 19,
                            cost: {
                                costNum: 350,
                            },
                        },
                    ],
                },
            ],
        };

        let resEle = document.querySelector(".result");

        // Using forEach method
        document.querySelector(".Btn").addEventListener("click", () => {
            resEle.innerHTML = "<h3>Using forEach():</h3>";
            json.storeData.forEach((store) => {
                store.items.forEach((item) => {
                    resEle.innerHTML += 
                        "Item ID: " + item.itemID + 
                        " | Cost: $" + item.cost.costNum + "<br>";
                });
            });
        });

        // Using map method
        document.querySelector(".MapBtn").addEventListener("click", () => {
            resEle.innerHTML = "<h3>Using map():</h3>";
            json.storeData.map((store) => {
                return store.items.map((item) => {
                    resEle.innerHTML += 
                        "Item ID: " + item.itemID + 
                        " | Cost: $" + item.cost.costNum + "<br>";
                    return item;
                });
            });
        });

        // Clear results
        document.querySelector(".ClearBtn").addEventListener("click", () => {
            resEle.innerHTML = "";
        });
    </script>
</body>
</html>

Using map() for Data Transformation

When you need to transform data and create new arrays, map() is more appropriate:

let json = {
    storeData: [
        {
            items: [
                { itemID: 12, cost: { costNum: 100 } },
                { itemID: 22, cost: { costNum: 250 } },
                { itemID: 19, cost: { costNum: 350 } }
            ]
        }
    ]
};

// Extract all item costs using map
let allCosts = json.storeData.map(store => 
    store.items.map(item => item.cost.costNum)
).flat();

console.log("All costs:", allCosts);

// Calculate total cost
let totalCost = allCosts.reduce((sum, cost) => sum + cost, 0);
console.log("Total cost:", totalCost);
All costs: [ 100, 250, 350 ]
Total cost: 700

Comparison: forEach vs map

Method Return Value Best Use Case Side Effects
forEach() undefined Performing actions on each element Usually has side effects
map() New array Transforming data Should avoid side effects

Practical Example: Filtering and Processing

let storeData = {
    storeData: [
        {
            items: [
                { itemID: 12, cost: { costNum: 100 }, category: "electronics" },
                { itemID: 22, cost: { costNum: 250 }, category: "clothing" },
                { itemID: 19, cost: { costNum: 350 }, category: "electronics" }
            ]
        }
    ]
};

// Find expensive electronics (cost > 150)
let expensiveElectronics = storeData.storeData
    .map(store => store.items)
    .flat()
    .filter(item => item.category === "electronics" && item.cost.costNum > 150);

console.log("Expensive electronics:", expensiveElectronics);
Expensive electronics: [ { itemID: 19, cost: { costNum: 350 }, category: 'electronics' } ]

Conclusion

Use forEach() when you need to perform actions on each element without creating new arrays, and map() when transforming data into new structures. Both methods are effective for parsing nested object arrays in JavaScript.

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

839 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements