Search code examples
arraysnestedjavascript-objects

How to find the sum of property values inside array nested within object


I am really new to javascript so forgive any mistakes in my presentation of my question. I have the following object and am trying to figure out how to find the sum quantity of all items. I am looking for the output of "17".

Here is the object:

const cart = {
    "tax": .10,
    "items": [
        {
            "title": "milk",
            "price": 4.99,
            "quantity": 2
        },
        {
            "title": "rice",
            "price": 0.99,
            "quantity": 2
        },
        {
            "title": "candy",
            "price": 0.99,
            "quantity": 3
        },
        {
            "title": "bread",
            "price": 2.99,
            "quantity": 1
        },
        {
            "title": "apples",
            "price": 0.75,
            "quantity": 9
        }
    ]
}

I have been working on finding solutions for the last 4 hours. This includes trying to find videos/written info on how to understand objects/arrays that are nested within properties. Any help in getting pointed in the right direction would be greatly appreciated. Thank you.


Solution

  • Loop through the "items" array and add all the quantities:

    let sum = 0;
    for(let i = 0; i < cart.items.length; i++){
         sum += cart.items[i].quantity;
    }
    
    console.log(sum) // Should be 17.