如何使用JavaScript从数组中获取总和?

时间:2018-07-19 16:10:42

标签: javascript ejs

SQL> select 'ÄÄÄÄ', dump('ÄÄÄÄ', 1016) from dual;

'ÄÄÄÄ' DUMP('ÄÄÄÄ',1016)
---- -----------------------------------------------
ÄÄÄÄ   Typ=96 Len=4 CharacterSet=AL32UTF8: c4,c4,c4,c4

我想获取每个名称或对象的膳食和押金的总和。

1 个答案:

答案 0 :(得分:0)

使用Array.mapArray.reduce

var data =[{name:"xyz",meals:[{num:3.5},{num:4 },{num:6.5},{num:3}],deposits:[{date:"", amount:3000},{date:"", amount:2400},{date:"", amount:300}]},{name:"abc",meals:[{num:3.5},{num:4 },{num:6.5},{num:3}],deposits:[{date:"", amount:3000},{date:"", amount:2400},{date:"", amount:300}]}];
    
let result = data.map(({name, meals, deposits}) => ({name, meals : meals.reduce((a,c) => a + c.num, 0), deposits : deposits.reduce((a,c) => a + c.amount, 0)}));
console.log(result);