0

晚上好,我需要按照他们的昵称对一组对象进行分组,这里我向您展示数据:

[
  {
    "nickName": "Info2",
    "countNotice": 4
  },
  {
    "nickName": "Info2",
    "countAlarm": 1
  }, 
  {
    "nickName": "Info1",
    "countNotice": 2
  },
  {
    "nickName": "Info1",
    "countAlarm": 3
  }
]

在这里,我向您展示了预期的结果:

[{
  "nickName": "Info1",
  "countNotice": 2,
  "countAlarm": 3
},
{
  "nickName": "Info1",
  "countAlarm": 1,
  "countNotice": 4
}]

我尝试在 NodeJs 中从 MongoDB 聚合,但这是不可能的。

4

2 回答 2

4

您可以分组,然后合并每个分组

const res = R.compose(
  R.map(R.mergeAll),
  R.values,
  R.groupBy(R.prop("nickName"))
)(data)

活生生的例子

const data = [
  {
    nickName: "Info2",
    countNotice: 4,
  },
  {
    nickName: "Info2",
    countAlarm: 1,
  },
  {
    nickName: "Info1",
    countNotice: 2,
  },
  {
    nickName: "Info1",
    countAlarm: 3,
  },
]

const res = R.compose(
  R.map(R.mergeAll),
  R.values,
  R.groupBy(R.prop("nickName"))
)(data)

console.log(res)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

于 2020-10-30T04:25:23.070 回答
1

使用Array.prototype.reduce,您可以按 对数组元素进行分组nickName

const input = [
  {
    "nickName": "Info2",
    "countNotice": 4
  },
  {
    "nickName": "Info2",
    "countAlarm": 1
  }, 
  {
    "nickName": "Info1",
    "countNotice": 2
  },
  {
    "nickName": "Info1",
    "countAlarm": 3
  }
];

const groupBy = input.reduce((acc, cur) => {
  acc[cur.nickName] ? acc[cur.nickName] = {
    ...acc[cur.nickName],
    ...cur
  } : acc[cur.nickName] = cur;
  return acc;
}, {});
const output = Object.values(groupBy);
console.log(output);

于 2020-10-30T04:25:28.187 回答