首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何减少包含匹配的键/值+ Variations的对象数组?

如何减少包含匹配的键/值+ Variations的对象数组?
EN

Stack Overflow用户
提问于 2021-03-25 18:59:36
回答 2查看 37关注 0票数 1

减少对象数组以获得所需结果的最佳方法是什么?

代码语言:javascript
复制
const arr = [
  {
          "id": "561",
          "count": "1",
          "month": 7
      },
      {
          "id": "561",
          "count": "1",
          "month": 7
      },
      {
          "id": "561",
          "count": "-1",
          "month": 8
      },
      {
          "id": "561",
          "count": "1",
          "month": 9
      },
      {
          "id": "561",
          "count": "-1",
          "month": 9
      }
  ]

正如您所看到的,id匹配和一些月份匹配。我想实现的目标大致如下:

代码语言:javascript
复制
[
  {
    "id": "561",
    "count": 2
    "month": 7
  },
  {
    "id": "561",
    "count": -1,
    "month": 8
  },
  {
    "id": "561",
    "count": 0,
    "month": 9
  }
]

我基本上是在尝试获取每个id按月计算的总数。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-03-25 19:06:18

您可以使用Array.prototype.reduce根据id和月份对数组进行分组和评估

代码语言:javascript
复制
const arr = [
  {
          "id": "561",
          "count": "1",
          "month": 7
      },
      {
          "id": "561",
          "count": "1",
          "month": 7
      },
      {
          "id": "561",
          "count": "-1",
          "month": 8
      },
      {
          "id": "561",
          "count": "1",
          "month": 9
      },
      {
          "id": "561",
          "count": "-1",
          "month": 9
      }
  ];
  
const res = Object.values(arr.reduce((acc, item) => {
   if (acc[`${item.id}-${item.month}`]) {
      acc[`${item.id}-${item.month}`] = {
        ...acc[`${item.id}-${item.month}`],
        count: `${parseInt(acc[`${item.id}-${item.month}`].count) + parseInt(item.count)}`
      }
   } else {
    acc[`${item.id}-${item.month}`] = item;
   }
   return acc;
}, {}));
console.log(res);

票数 2
EN

Stack Overflow用户

发布于 2021-03-25 19:07:11

下面是一个使用Array.prototype.reduce创建新数组并使用Array.prototype.find检查当前值是否已存在于新数组中的示例

代码语言:javascript
复制
const arr = [
  {
          "id": "561",
          "count": "1",
          "month": 7
      },
      {
          "id": "561",
          "count": "1",
          "month": 7
      },
      {
          "id": "561",
          "count": "-1",
          "month": 8
      },
      {
          "id": "561",
          "count": "1",
          "month": 9
      },
      {
          "id": "561",
          "count": "-1",
          "month": 9
      }
  ]

const result = arr.reduce((acc, value) => {
  const index = acc.findIndex(({id, month}) => id === value.id && month === value.month);
  if( index > -1 ) {
    acc[index]['count'] += Number(value.count);
  }
  else {
    acc.push({...value, count: Number(value.count)});
  }
  return acc;
}, [])

console.log(result)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66798079

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档