简体   繁体   中英

How to sum all of values from specific key in object?

Let's say I have a array that contains a multiple object like:

var arr = [{ 'credit': 1, 'trash': null }, { 'credit': 2, 'trash': null}]

I want to get a sum of all credit value from arr array. so expected sum value is 3. so I used this code:

arr.reduce((obj, total) => obj.credit + total)

but when I run this, I get "1[object Object]" which is really weird.

Ps: I'm trying to implement this using ES6 not ES5

Two problems: your total and obj arguments are backwards, and you need to provide something to initialize the total variable (that's the ,0 part)

arr.reduce((total, obj) => obj.credit + total,0)
// 3

You can use .forEach() here:

 var arr = [{ 'credit': 1, 'trash': null }, { 'credit': 2, 'trash': null}]; var total = 0; arr.forEach(item => { total += item.credit; }); console.log(total); 

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