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

Time:11-16

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.

CodePudding user response:

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.

CodePudding user response:

You have to use below code with best practices.

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
    }
]};

let items = cart.items;
let sum = 0;
items.forEach(function(item){
    sum  = item.quantity
});
console.log(sum)
  • Related