How to group or merge this array of objects in jav

2020-02-13 07:46发布

I have an array of objects like below for example.

{name: "Mc Donald", quantity: 4, maleCount: 1, femaleCount: 0}
{name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0}
{name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0}
{name: "Mc Donald", quantity: 4, maleCount: 0, femaleCount: 1}
{name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1}
{name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0}
{name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1}
{name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1}

I want to group them up and adding up all the values in it. For example, the final would be like this:

{name: "Mc Donald", quantity: 8, maleCount: 1, femaleCount: 1}
{name: "KFC", quantity: 54, maleCount: 3, femaleCount: 3}

How can I achieve this in JavaScript?

I have tried to find some solution online but it is not the one I wanted. For example this solution

8条回答
神经病院院长
2楼-- · 2020-02-13 08:17

More functional/universal approach

const normalizeValue = (value) => value === undefined ? 0 : value
const sumUpProps = (props = []) => (a = {}, b = {}) => {
  const result = {}
  
  props.forEach((prop) => {
    result[prop] = normalizeValue(a[prop]) + normalizeValue(b[prop])
  })

  return result
}

const data = [
  {name: "Mc Donald", quantity: 4, maleCount: 1, femaleCount: 0},
  {name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
  {name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
  {name: "Mc Donald", quantity: 4, maleCount: 0, femaleCount: 1},
  {name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1},
  {name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
  {name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1},
  {name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1}
]

const entries = {}
const sumObjects = sumUpProps(['quantity', 'maleCount', 'femaleCount'])

data.forEach((item) => {
  const entry = entries[item.name] || {}

  entries[item.name] = sumObjects(entry, item)
})


console.log(entries)

查看更多
劳资没心,怎么记你
3楼-- · 2020-02-13 08:31

Lodash makes your life easy.

_.map(_.groupBy(yourArrayHere, 'name'), (groupMembers, groupKey) => {
    let sumObject = {name: groupKey};

    _.forEach(['quantity', 'maleCount', 'femaleCount'], (property) => {
        sumObject[property] = 0;
        _.forEach(groupMembers, (member) => {
            sumObject[property] += member[property];
        });
    });

    return sumObject;
});
查看更多
登录 后发表回答