从对象数组中计算2个对象键/列 [英] Calculating 2 object keys/columns from array of objects Javascript

查看:46
本文介绍了从对象数组中计算2个对象键/列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在进行某些列合并和过滤的工作,但是在从对象数组中计算2个对象键(列),然后将结果映射到对象键到新数组时遇到困难

So I was working on the some column merging and filtering,but I am having trouble calculating 2 object keys (columns) from an array of objects and then mapping that result to an object key to a new array

示例:

var foodRevenue = [{
    "Month": "2011-01",
    "week1_Revenue": "100.00",
    "week2_Revenue": "300.51",
    "Week3_Reenue": "200.09",
    "Month1_TotalRevenue": "0"
}];

我想计算 week1 week2 week3 的总和,并将结果映射到 Month1_TotalRevenue .然后创建一个新数组,将Month和Month1_TotalRevenue过滤到该数组.像这样:

I want to calculate the sum of week1, week2, and week3 and the result to map on Month1_TotalRevenue. Then creating a new array that would filter Month and Month1_TotalRevenue to that array. Like so:

{"Month": "2011-01", "Month1_TotalRevenue": "600.60"}

任何建议将不胜感激

推荐答案

您可以使用 Array.prototype.reduce()解构对象的属性并汇总所需的属性:

You may destructure your object properties and sum up desired ones, using Array.prototype.reduce():

const  foodRevenue = {
      "Month": "2011-01",
      "week1_Revenue": "100.00",
      "week2_Revenue": "300.51",
      "Week3_Reenue": "200.09",
      "Month1_TotalRevenue": "0"
    },
    {Month, Month1_TotalRevenue, week1_Revenue,...revenue} = foodRevenue,
    result = {
      Month,
      week1_Revenue,
      Month1_TotalRevenue: 
        Object
          .values({...revenue,week1_Revenue})
          .reduce((s,r) => s+=+r, +Month1_TotalRevenue)
          .toFixed(2)
    }
    
console.log(result)

这篇关于从对象数组中计算2个对象键/列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆