I have currently two objects in my cartProducts array and the size will grow more in future. I am trying to calculate the sum of all items prices in products for all the objects. I have tried to use forEach but it seems to work slowly. How can I calculate the sum of prices in a faster way? I saw that using reduce is fine but as there are a lot of nested objects, I cannot figure out how to use it.
{
    "cartProducts": [
        {
            "id": "1",
            "products": [
                {
                    "id": "123",
                    "supplier": "Milkinis",
                    "items": [
                        {
                            "id": "14553",
                            "name": "eggs",
                            "price": "1.56",
                        },
                        {
                            "id": "14554",
                            "name": "flour",
                            "price": "1.98",
                        },
                    ]
                },
                {
                    "id": "124",
                    "supplier": "Lindy",
                    "items": [
                        {
                            "id": "14553",
                            "name": "chocolate",
                            "price": "4.5",
                        },
                    ]
                }
            ]
        },
        {
            "id": "2",
            "products": [
                {
                    "id": "125",
                    "supplier": "Wisk",
                    "items": [
                        {
                            "id": "14553",
                            "name": "water",
                            "price": "3.56",
                        },
                    ]
                }
            ]
        },
    ]
}


forEachis perfectly good for this, or afor-ofloop, or just a basicforloop. Despite the factforEachcalls a function, the cost of that is really low and really unlikely to matter. (The nesting argues for recursion, notreduce.reduceis fine in its context -- functional programming with predefined, reusable reducer functions -- but otherwise it's just an overcomplicated, easy-to-get-wrong loop.)data.cartProducts.reduce((g,{products})=>g+products.reduce((i,{items})=>i+items.reduce((p,{price})=>+price+p,0),0),0);