最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to sum the array of object values and assigned them to the relevant key name - Stack Overflow

programmeradmin3浏览0评论

I need to understand the simplest way of doing this. I've got an array of objects:

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

What I'm trying to get is simple object where its key is the month from data.ines and the value is sum of relative month values, so the final result looks like:

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

Can anybody explain it to me step by step, please?

I need to understand the simplest way of doing this. I've got an array of objects:

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

What I'm trying to get is simple object where its key is the month from data.ines and the value is sum of relative month values, so the final result looks like:

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

Can anybody explain it to me step by step, please?

Share Improve this question asked Jan 20, 2022 at 16:52 dariuszdariusz 5931 gold badge6 silver badges18 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 3

solved using reduce and forEach

Inside the reduce function I'm running a forEach on the array of keys of the ines object/attribute. For each key which is a date I'm checking if the accumulator of the reduce function contains an attribute for each date and creates if not. After creating the attribute I'm summing the value for the current date attribute.

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

const totalInes = data.reduce((acc, curr) => {
  Object.keys(curr.ines).forEach((key, index) => {
    if (!acc[key]) {
      acc[key] = 0
    }
    acc[key] += curr.ines[key]
  })
  return acc
}, {})

console.log(totalInes)

Maybe this is not the pretties solutions but you can do it like this, the function is of course not necessary.

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

getterInformation(data);

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

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

      objectWithCalculatedValues[key] += items.ines[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 aggregateInesByMonth = () => (
  data.map(d => Object.entries(d.ines).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 ines from the data array
  2. For each ine object, get the key-value pair and transform into another object of the structure {key: 20yy-mm, value: nn}
  3. Use .flat() to transform the result from step-2 into a 1-dimensional array
  4. Use .reduce to sum the value for those cases where the key (ie, 20yy-mm) matches.

Code-snippet

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

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

console.log(aggregateInesByMonth());

My approach here is to destructure the array. This way I have all the data of the ines of group A in the variable A and the same for B.

Then I do a double loop to pare both objects data and see if the dates match. If so, sum the ines and add the data to the total object.

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

let A, B, total = {};

[A, B] = [data[0].ines, data[1].ines]

for(const date in A){
  for(const d in B){
   total[date] = date === d ? A[date] + B[date] : A[date]
  }  
}

console.log(total)

发布评论

评论列表(0)

  1. 暂无评论