gpt4 book ai didi

Javascript 如何将 JSON 中的事件拆分为几个月

转载 作者:行者123 更新时间:2023-12-03 03:23:22 25 4
gpt4 key购买 nike

我想根据事件发生的月份显示事件列表。现在它是一个带有 JSON 的数组,其中每个事件都作为一个对象包含在内,但因为我想像这样显示它:

January
- event blabla 10/01/17
- event thisandthat 17/01/17

February
- event something 05/02/17
- event another something 13/02/17

...etc etc

我无法像我想要的那样使用 JSON 。那么有没有办法可以“更改”JSON以满足我的需要?

现在我收到这样的 JSON:

[{
"event_name": "blabla",
"event_location" : "somewhere",
"event_date": "2017-01-10"
},
{
"event_name": "blabla",
"event_location" : "somewhere",
"event_date": "2017-01-10"
},
{
"event_name": "blabla",
"event_location" : "somewhere",
"event_date": "2017-02-10"
},
{
"event_name": "blabla",
"event_location" : "somewhere",
"event_date": "2017-03-20"
},
{
"event_name": "blabla",
"event_location" : "somewhere",
"event_date": "2017-05-05"
}]

我想要的结果应该是这样的:

[{
"January": [{
"event_name": "blabla",
"event_location" : "somewhere",
"event_date": "2017-01-10"
},
{
"event_name": "blabla",
"event_location" : "somewhere",
"event_date": "2017-01-17"
}
]
},
{
"February": [{
"event_name": "blabla",
"event_location" : "somewhere",
"event_date": "2017-02-10"
},
{
"event_name": "blabla",
"event_location" : "somewhere",
"event_date": "2017-02-17"
}
]
},
{
"March": [{
"event_name": "blabla",
"event_location" : "somewhere",
"event_date": "2017-03-10"
},
{
"event_name": "blabla",
"event_location" : "somewhere",
"event_date": "2017-03-17"
}
]
}
]

我怎样才能实现这个目标(如果可能的话)?

最佳答案

您可以使用 Array#reduce 来实现此目的:

var data = [{
"event_name": "blabla",
"event_location" : "somewhere",
"event_date": "2017-01-10"
},
{
"event_name": "blabla",
"event_location" : "somewhere",
"event_date": "2017-10-17"
},
{
"event_name": "blabla",
"event_location" : "somewhere",
"event_date": "2017-02-10"
},
{
"event_name": "blabla",
"event_location" : "somewhere",
"event_date": "2017-03-20"
},
{
"event_name": "blabla",
"event_location" : "somewhere",
"event_date": "2017-05-05"
}];

var monthName = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var groups = data.reduce(function(acc, o) {
var month = monthName[new Date(o.event_date).getMonth()];
acc[month] = acc[month] || [];
acc[month].push(o);
return acc;
}, {});

var result = Object.keys(groups).sort(function(a, b) {
return monthName.indexOf(a) - monthName.indexOf(b);
}).map(function(key) {
var o = {};
o[key] = groups[key];
return o;
});

console.log(result);

关于Javascript 如何将 JSON 中的事件拆分为几个月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46468006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com