javascript - 根据对象中键的值对数组中的对象进行分组
问题描述
我有以下要根据日期排序的数据 - 不包括时间戳。
注意:我有权moment
执行此任务。
我的数据如下所示:
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",
}
];
我尝试了多种方法。我希望达到的最终结果是以下数据结构。
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",
}]
},
];
这是我最近的尝试,几乎奏效了:
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));
解决方案
您可以将使用的数组分组reduce
到一个对象中。使用Object.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",
}
];
const result = Object.values(data.reduce((c, v) => {
let t = v['kickOffTime'].split('T', 1)[0];
c[t] = c[t] || {date: t,fixtures: []}
c[t].fixtures.push(v);
return c;
}, {}));
console.log(result);
推荐阅读
- sql - 如何使用一个选择查询在买卖双方之间进行交流
- python - 如何用谷歌翻译器翻译单词?
- c - 初始化二维数组的函数
- xml - XSLT:将平面 XML 转换为分层 XML
- .net-core - 处理 .net core 2.1 web api 中的无效请求错误
- c# - 字典初始化问题
- mysql - SQL - 显示分组值从一组到另一组的变化(取决于时间)
- php - mysqli_connect 错误 2002“没有这样的文件或目录”Mac OS 10.13.2
- java - 如何在另一个 JTable 的单元格中实现 JTable 以及如何从数据库中实现列名?
- sql - Left(null,5) <> 'anything' 不正确?[T-SQL]