通过通用键和值组合数组中的对象

时间:2019-05-26 09:44:13

标签: javascript arrays object

我有一个数据集,一个对象数组,我需要通过一个公用键(日期)进行组合,然后将UserName合并为UserScore的键。 我打算用d3绘制这些数据,并使用d3的某些方法来解决,但想用vanilla JS编写它。这是原始数据的示例

[
  {
    "Date": "2019-05-02 00:00:00 UTC",
    "UserName": "user1",
    "UserScore": "39"
  },
  {
    "Date": "2019-05-02 00:00:00 UTC",
    "UserName": "user2",
    "UserScore": "11"
  },
  {
    "Date": "2019-05-02 00:00:00 UTC",
    "UserName": "user3",
    "UserScore": "4"
  },
  {
    "Date": "2019-05-02 01:01:01 UTC",
    "UserName": "user1",
    "UserScore": "57"
  },
  {
    "Date": "2019-05-02 01:01:01 UTC",
    "UserName": "user2",
    "UserScore": "1"
  },
  {
    "Date": "2019-05-02 01:01:01 UTC",
    "UserName": "user3",
    "UserScore": "42"
  }
]

这是我想要的输出

   {
    "Date": "2019-05-02 00:00:00 UTC",
    "user1": "39",
    "user2": "11",
    "user3": "4"
   },
   {
    "Date": "2019-05-02 01:01:01 UTC",
    "user1": "57",
    "user2": "1",
    "user3": "42"
   }
]

1 个答案:

答案 0 :(得分:0)

您可以使用reduce()对其进行分组。

const arr = [ { "Date": "2019-05-02 00:00:00 UTC", "UserName": "user1", "UserScore": "39" }, { "Date": "2019-05-02 00:00:00 UTC", "UserName": "user2", "UserScore": "11" }, { "Date": "2019-05-02 00:00:00 UTC", "UserName": "user3", "UserScore": "4" }, { "Date": "2019-05-02 01:01:01 UTC", "UserName": "user1", "UserScore": "57" }, { "Date": "2019-05-02 01:01:01 UTC", "UserName": "user2", "UserScore": "1" }, { "Date": "2019-05-02 01:01:01 UTC", "UserName": "user3", "UserScore": "42" } ]

const res = arr.reduce((ac,{Date,UserName,UserScore}) => {
  ac[Date] = ac[Date] || {Date};
  ac[Date][UserName] = UserScore;
  return ac;
},{})

console.log(Object.values(res))