根据对象中键的值对数组中的对象进行分组 [英] group objects in array based on value of key in object

查看:167
本文介绍了根据对象中键的值对数组中的对象进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据要根据日期排序 - 不包括时间戳。

I have the following data that I want to sort based on the date - not including the timestamp.

注意:此任务我可以访问时刻

我的数据如下所示:

const data = [
   {
     "fixture": "AC v Inter",
     "kickOffTime": "2018-06-14T15:00:00Z",
   },
   {
     "fixture": "DC v NYC",
     "kickOffTime": "2018-06-15T12:00:00Z",
   },
   {
     "fixture": "AFC v LPC",
     "kickOffTime": "2018-06-15T15:00:00Z",
   },
   {
      "fixture": "DTA v MC",
      "kickOffTime": "2018-06-15T18:00:00Z",
    },
    {
       "fixture": "LAC v GC",
       "kickOffTime": "2018-06-16T18:00:00Z",
    }
];

我尝试了很多方法。我希望实现的最终结果是以下数据结构。

I have tried a number of approaches. The final result I am hoping to achieve is the following data structure.

const updatedDataStructure = [
   {
     date: "2018-06-14",
     fixtures: [{
        "fixture": "AC v Inter",
        "kickOffTime": "2018-06-14T15:00:00Z",
      }]
   },
   {
     date: "2018-06-15",
     fixtures: [
      {
        "fixture": "DC v NYC",
        "kickOffTime": "2018-06-15T12:00:00Z",
       }, 
      {
        "fixture": "AFC v LPC",
       "kickOffTime": "2018-06-15T15:00:00Z",
      },
      {
        "fixture": "DTA v MC",
        "kickOffTime": "2018-06-15T18:00:00Z",
       },
     ]
   }, 
   {
     date: "2018-06-16",
     fixtures: [{
         "fixture": "LAC v GC",
         "kickOffTime": "2018-06-16T18:00:00Z",
     }]
   },
];

这是我最近的尝试,近乎有效:

Here was my latest attempt which NEARLY worked:

const result = fixtures.reduce(function (r, a) {
  r[moment(a.kickOffTime).format('ddd Do MMM')] = r[moment(a.kickOffTime).format('ddd Do MMM')] || [];
  r[moment(a.kickOffTime).format('ddd Do MMM')].push(a);
  return r;
}, Object.create(null));


推荐答案

您可以从日期开始,稍后获取对象的条目并映射新的键/值。

You could take just a slice from the date and later take the entries of the object and map new key/values.

 const
     data = [{ fixture: "AC v Inter", kickOffTime: "2018-06-14T15:00:00Z" }, { fixture: "DC v NYC", kickOffTime: "2018-06-15T12:00:00Z" }, { fixture: "AFC v LPC", kickOffTime: "2018-06-15T15:00:00Z" }, { fixture: "DTA v MC", kickOffTime: "2018-06-15T18:00:00Z" }, { fixture: "LAC v GC", kickOffTime: "2018-06-16T18:00:00Z" }];
     result = Object
        .entries(data.reduce((r, a) => {
            var key = a.kickOffTime.slice(0, 10);
            r[key] = r[key] || [];
            r[key].push(a);
            return r;
        }, Object.create(null)))
        .map(([date, fixtures]) => ({ date, fixtures }));

console.log(result);

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

这篇关于根据对象中键的值对数组中的对象进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆