作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想根据事件发生的月份显示事件列表。现在它是一个带有 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/
我是一名优秀的程序员,十分优秀!