【问题标题】:Sum array properties into a new array将数组属性汇总到一个新数组中
【发布时间】:2020-09-15 14:59:50
【问题描述】:

我有一个具有以下属性的对象:

myCosts {
 monthlyCost: {
   currency: EUR,
   amount: 10,
 },
weeklyCosts: {
   currency: EUR,
   amount: 100,
 }
}

我需要创建一个新的对象/数组,它具有相同的类型和属性,只是金额是 myCosts.monthlyCost.amount + myCosts.weeklyCosts.amount 的总和。

所以它会是这样的:

sumCosts {
  monthlyCosts: {
    currency: EUR,
    amount: 110
  }
}

【问题讨论】:

  • 如果是每周的费用,加起来不应该是410吗?
  • 为什么需要按月计费?
  • 在下面查看我的解决方案

标签: javascript object


【解决方案1】:

首先,您使用的不是数组而是对象。

您仍然可以使用Object.entries()reduce 函数来获得所需的输出。

const myCosts = {
 monthlyCost: {
   currency: 'EUR',
   amount: 10,
 },
 weeklyCosts: {
   currency: 'EUR',
   amount: 100,
 }
};

const result = Object.entries(myCosts)
    .reduce((acc, [curKey, curValue]) => {      
      if(curKey.localeCompare('amount')) {    
        acc.montlyCosts.amount += curValue.amount;
      }
      return acc;
    }, 
    {montlyCosts: {currency: 'EUR', amount: 0}}
);

【讨论】:

    【解决方案2】:
    function transformCost(myCost) {
       var arr = [...Object.entries(myCost).map((obj)=>obj[1])];
       var sum = arr.reduce((prev,next) => (prev + (next.amount)), 0);
       return {
                monthlyCost: {
                      currency: arr[0].currency,
                      amount: sum
                }
              };
    }
    

    【讨论】:

      【解决方案3】:

      使用reduce

      const myCosts = {
        monthlyCost: {
          currency: 'EUR',
          amount: 10,
        },
        weeklyCosts: {
          currency: 'EUR',
          amount: 100,
        },
      };
      
      const sumCost = {
        monthlyCosts: {
          currency: 'EUR',
          amount: Object.entries(myCosts).reduce(
            (acc, [, {amount}]) => acc + amount,
            0
          ),
        },
      };
      
      console.log(sumCost);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-21
        • 2019-02-27
        • 2017-10-13
        • 2023-01-20
        • 1970-01-01
        • 2012-12-19
        • 2020-07-04
        相关资源
        最近更新 更多