[英]group objects in array based on value of key in object
我有以下数据,我想根据日期排序 - 不包括时间戳。
注意:我可以访问此任务的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);
您可以从日期中获取一个切片,然后获取对象的条目并映射新的键/值。
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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.