How to get sum from array using javascript?

China☆狼群 提交于 2019-12-25 19:35:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!