简体   繁体   English

如何对 object 值的数组求和并将它们分配给相关的键名

[英]How to sum the array of object values and assigned them to the relevant key name

I need to understand the simplest way of doing this.我需要了解执行此操作的最简单方法。 I've got an array of objects:我有一个对象数组:

const data = [
  {
    group: 'A',
    incomes: {
      "2019-12": 100,
      "2020-12": 200,
      "2021-12": 15
    }
  },
  {
    group: 'B',
    incomes: {
      "2019-12": 25,
      "2020-12": 50,
    }
  }
]

What I'm trying to get is simple object where its key is the month from data.incomes and the value is sum of relative month values, so the final result looks like:我想要得到的是简单的 object ,其中它的键是来自 data.incomes 的月份,值是相对月份值的总和,所以最终结果如下所示:

const totalIncomes = {
  "2019-12": 125,
  "2020-12": 250,
  "2021-12": 15
}

Can anybody explain it to me step by step, please?有人可以一步一步地向我解释吗?

solved using reduce and forEach使用 reduce 和 forEach 解决

 const data = [ { group: 'A', incomes: { "2019-12": 100, "2020-12": 200, "2021-12": 15 } }, { group: 'B', incomes: { "2019-12": 25, "2020-12": 50, } } ] const totalIncomes = data.reduce((acc,curr)=> { Object.keys(curr.incomes).forEach((key, index) => { if(;acc[key]){ acc[key] = 0. } acc[key]+=curr;incomes[key] }); return acc, }.{}) console.log(totalIncomes)

Maybe this is not the pretties solutions but you can do it like this, the function is of course not necessary.也许这不是漂亮的解决方案,但你可以这样做,function 当然不是必需的。

const data = [
  {
    group: "A",
    incomes: {
      "2019-12": 100,
      "2020-12": 200,
      "2021-12": 15,
    },
  },
  {
    group: "B",
    incomes: {
      "2019-12": 25,
      "2020-12": 50,
    },
  },
];

getterInformation(data);

function getterInformation(object) {
  let objectWithCalculatedValues = {};

  object.forEach((items) => {
    for (const key in items.incomes) {
      if (objectWithCalculatedValues[key] === undefined) {
        objectWithCalculatedValues[key] = 0;
      }

      objectWithCalculatedValues[key] += items.incomes[key];
    }
  });

  console.log(objectWithCalculatedValues);
}

Assuming that this information may be useful to readers who may be unable to obtain necessary guidance (due to various possible reasons), here is one possible way to achieve the objective (solution):假设此信息可能对可能无法获得必要指导的读者有用(由于各种可能的原因),以下是实现目标的一种可能方法(解决方案):

const aggregateIncomesByMonth = () => (
  data.map(d => Object.entries(d.incomes).map(([k, v]) => ({
    key: k,
    value: v
  }))).flat().reduce((fin, itm) => ({
    ...fin,
    [itm.key]: (fin[itm.key] || 0) + itm.value
  }), {})
);

Explanation解释

  1. Extract only the incomes from the data array仅从data数组中提取incomes
  2. For each income object, get the key-value pair and transform into another object of the structure {key: 20yy-mm, value: nn}对于每一个income object,得到key-value对,转化为另一个结构{key: 20yy-mm, value: nn}
  3. Use .flat() to transform the result from step-2 into a 1-dimensional array使用.flat()将步骤 2 的结果转换为一维数组
  4. Use .reduce to sum the value for those cases where the key (ie, 20yy-mm) matches.使用.reducekey (即 20yy-mm)匹配的那些情况的value求和。

Code-snippet代码片段

 const data = [{ group: 'A', incomes: { "2019-12": 100, "2020-12": 200, "2021-12": 15 } }, { group: 'B', incomes: { "2019-12": 25, "2020-12": 50, } } ]; const aggregateIncomesByMonth = () => ( data.map(d => Object.entries(d.incomes).map(([k, v]) => ({ key: k, value: v }))).flat().reduce((fin, itm) => ({...fin, [itm.key]: (fin[itm.key] || 0) + itm.value }), {}) ); console.log(aggregateIncomesByMonth());

My approach here is to destructure the array.我的方法是解构数组。 This way I have all the data of the incomes of group A in the variable A and the same for B .这样,我在变量A中获得了 A 组收入的所有数据,对于B也是如此。

Then I loop through both objects and see if the dates match, if so, sum the incomes and add the data to the total object.然后我遍历这两个对象并查看日期是否匹配,如果匹配,则将收入相加并将数据添加到total object。

 const data = [ { group: 'A', incomes: { "2019-12": 100, "2020-12": 200, "2021-12": 15 } }, { group: 'B', incomes: { "2019-12": 25, "2020-12": 50 } } ] let A, B, total = {}; [A, B] = [data[0].incomes, data[1].incomes] for(const date in A){ for(const d in B){ total[date] = date === d? A[date] + B[date]: A[date] } } console.log(total)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM