javascript - 如何获取对象数组中键的总和并删除连续对象的重复项?

标签 javascript arrays ecmascript-6 javascript-objects

<分区>

我有一个主数组-

const arr = [
    {  description: 'Senior', amount: 50 },
    {  description: 'Senior', amount: 50 },
    {  description: 'Adult', amount: 75 },
    {  description: 'Adult', amount: 35 },
    {  description: 'Infant', amount: 25 },
    {  description: 'Senior', amount: 150 }
]

我需要有关 es6 操作的帮助,该操作将根据键(描述)添加数量并删除重复项。

结果数组看起来有点像-

const newArr = [
        {  description: 'Senior', amount: 120 },
        {  description: 'Adult', amount: 110 },
        {  description: 'Infant', amount: 25 },
        {  description: 'Senior', amount: 150 }
]

我一直在使用 reduce 运算符通过下面的解决方案来实现这一点,但这也会删除不连续的对象。

如果有人可以帮助我使用一些 es6 运算符来执行相同的操作,那将非常有帮助。

最佳答案

const arr = [
  { description: "Senior", amount: 50 },
  { description: "Senior", amount: 50 },
  { description: "Adult", amount: 75 },
  { description: "Adult", amount: 35 },
  { description: "Infant", amount: 25 },
];

const result = Object.values(
  arr.reduce((acc, item) => {
    acc[item.description] = acc[item.description]
      ? { ...item, amount: item.amount + acc[item.description].amount }
      : item;
    return acc;
  }, {})
);

console.log(result);

关于javascript - 如何获取对象数组中键的总和并删除连续对象的重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70296196/

相关文章:

c - 分割一个字符串并存储在数组的数组中

java - 如何从文件中获取信息(字母和整数),并存储该信息以供进一步使用?

java - 如何使用 JNA StdCallCallback 接受结构中的 int 数组?

javascript - 从另一个模块导出模块类

javascript - CSS - 将整个图像显示为背景而不裁剪

javascript - d3.timeScale() X轴不显示年份

javascript - 从另一个对象数组中删除对象数组

javascript - 这行代码是什么意思? const {"intl": { formatMessage }, } = this.context

javascript - 使用 Babel 在线将 ES6 编译成 ES5

javascript - 检测图像链接并嵌入它们