简体   繁体   中英

How to sum the values of multiple items in a JavaScript object?

I'd like to sum the values of multiple objects.

I have an array of example 3 items, this varies and can be any number.

_items: 
0: {...}
1: {...}
2: {...}

Each of these item then has the following data:

0: 
dayOfYear: 357
dayOfWeek: 4
noOfUnits: "11"
_id: "12345"
_owner: "12345"
_createdDate: "Thu Dec 23 2021"
year: 2021
_updatedDate: "Thu Dec 23 2021"
week: 51
userId: "12345"
type: "Type 1"

I'd like to add the values of the noOfUnits variable. So for example in item 0 value is 11 , item 1 is 2 and item 2 is 5 . The total would become 18 . This is not limited to 3 items but varies according to the number of items pulled from a database.

Thanks and happy holidays!

You can reduce it

        const results = [
            {noOfUnits: "11"},
            {noOfUnits: "2"},
            {noOfUnits: "5"},
        ]
        console.log(results.reduce((acc, curr) => acc + Number(curr.noOfUnits), 0))

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM