问题
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},
];
}
];
I want to get the sum of meals & deposits for every name or object.
回答1:
Use Array.map and Array.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);
来源:https://stackoverflow.com/questions/51427402/how-to-get-sum-from-array-using-javascript