如何按对象属性值对对象数组进行分组?

时间:2020-03-14 19:49:06

标签: javascript arrays react-native grouping

我有这样的JSON:

[
  {
    "id": 9,
    "job_id": 302,
    "user_id": 63,
    "message": "User message 1",
    "created_at": 1584091342
  },
  {
    "id": 10,
    "job_id": 302,
    "user_id": 63,
    "message": "User message 2",
    "created_at": 1584095994
  },
  {
    "id": 14,
    "job_id": 302,
    "user_id": 63,
    "message": "Hello",
    "created_at": 1584102257
  },
]

如何按日期对消息进行分组,类似这样? (我正在使用moment.js格式化unix时间戳)

enter image description here

1 个答案:

答案 0 :(得分:2)

为此,我们可以使用数组函数reduce:

我们还需要将您的数据以毫秒为单位转换为几天。

const data = [
  {
    "id": 9,
    "job_id": 302,
    "user_id": 63,
    "message": "User message 1",
    "created_at": 1584130559280
  },
  {
    "id": 10,
    "job_id": 302,
    "user_id": 63,
    "message": "User message 2",
    "created_at": 1584130559280
  },
  {
    "id": 14,
    "job_id": 302,
    "user_id": 63,
    "message": "Hello",
    "created_at": 1584216959280
  },
  {
    "id": 15,
    "job_id": 302,
    "user_id": 63,
    "message": "World",
    "created_at": 1584216959280
  }  
]

const groupedData = data.reduce((aggObj, child) => {
  const myDate = new Date(child.created_at);
  //console.log(myDate.toDateString());
  //console.log(myDate.getTime());
  if (aggObj.hasOwnProperty(myDate.toDateString())){
    aggObj[myDate.toDateString()].push(child);
  } else {
    aggObj[myDate.toDateString()] = [child];
  }    
  return aggObj
}, {})

console.log(groupedData);
.as-console-wrapper { max-height: 100% !important; top: 0; }

我更改了created_at值,因此前两个消息来自昨天,后两个消息来自今天。

输出为:

{
  "Fri Mar 13 2020": [
    {
      "id": 9,
      "job_id": 302,
      "user_id": 63,
      "message": "User message 1",
      "created_at": 1584130559280
    },
    {
      "id": 10,
      "job_id": 302,
      "user_id": 63,
      "message": "User message 2",
      "created_at": 1584130559280
    }
  ],
  "Sat Mar 14 2020": [
    {
      "id": 14,
      "job_id": 302,
      "user_id": 63,
      "message": "Hello",
      "created_at": 1584216959280
    },
    {
      "id": 15,
      "job_id": 302,
      "user_id": 63,
      "message": "World",
      "created_at": 1584216959280
    }
  ]
}