对象数组中相似项的总和

时间:2021-04-16 10:11:32

标签: javascript node.js arrays object sum

我怎样才能转动这个数组:

[
  { cat: 'Uncategorized', amount: 60 },
  { cat: 'Auto & Transport', amount: 28.01 },
  { cat: 'Auto & Transport', amount: 10.57 },
  { cat: 'Shopping', amount: 7.96 },
  { cat: 'Uncategorized', amount: 100 }
]

进入这个:

[
  { cat: 'Uncategorized', amount: 160},
  { cat: 'Auto & Transport', amount: 38.58 },
  { cat: 'Shopping', amount: 7.96 },   
]

其实我想把同一个猫的物品相加

提前致谢

3 个答案:

答案 0 :(得分:0)

您可以使用 reduce

const arr = [{
    cat: "Uncategorized",
    amount: 60
  },
  {
    cat: "Auto & Transport",
    amount: 28.01
  },
  {
    cat: "Auto & Transport",
    amount: 10.57
  },
  {
    cat: "Shopping",
    amount: 7.96
  },
  {
    cat: "Uncategorized",
    amount: 100
  },
];

const result = arr.reduce((acc, { cat, amount }) => {
  const prop = acc.find((o) => o.cat === cat);
  if (!prop) {
    acc.push({ cat, amount });
  } else {
    prop.amount += amount;
  }
  return acc;
}, []);

console.log(result);

答案 1 :(得分:0)

您可以将数组缩减为一个对象,使用 cat 作为键对 amount 求和。然后,使用 Array.values():

将对象转换回数组

const unOrgArray = [{"cat":"Uncategorized","amount":60},{"cat":"Auto & Transport","amount":28.01},{"cat":"Auto & Transport","amount":10.57},{"cat":"Shopping","amount":7.96},{"cat":"Uncategorized","amount":100}]

const result = Object.values(unOrgArray.reduce((acc, obj) => {
  if(!acc[obj.cat]) // if the object doesn't exist on the accumulator
    acc[obj.cat] = { ...obj } // clone the current object
  else // if it does exist
    acc[obj.cat].amount += obj.amount // add the amount to the sum
  
  return acc
}, {}))

console.log(result)

答案 2 :(得分:0)

您可以使用 Array.reduce 按类别对列表进行分组。

然后使用 Object.entriesArray.map 将它们转换为数组

const list = [
  { cat: 'Uncategorized', amount: 60 },
  { cat: 'Auto & Transport', amount: 28.01 },
  { cat: 'Auto & Transport', amount: 10.57 },
  { cat: 'Shopping', amount: 7.96 },
  { cat: 'Uncategorized', amount: 100 }
];

console.log(
  Object.entries(
    list.reduce((acc, item) => ({ ...acc, [item.cat]: (acc[item.cat] || 0) + item.amount }), {}),
  ).map((entry) => ({
    cat: entry[0],
    amount: entry[1],
  })),
);