Mer*_*ial 5 javascript jquery json
[{"id":"15","heading":"Post1","content":"Post 1 Content","date":"2016-11-09 08:51:37"},
{"id":"16","heading":"Post2","content":"Post 2 Content","date":"2016-11-09 08:52:09"},
{"id":"17","heading":"Post3","content":"Post 3 Content","date":"2015-06-09 08:52:09"}]
Run Code Online (Sandbox Code Playgroud)
我有JSON数组.我试图将其转换为JSON对象
2016
Nov
Post1
Post2
2015
June
Post3
Run Code Online (Sandbox Code Playgroud)
我能够在PHP中实现这一目标
while ($row = mysqli_fetch_row($result)) {
$year = date('Y', strtotime($row['2']));
$month = date('M', strtotime($row['2']));
$navarray[$year][$month][] = array($row[0], $row[1], $row[3]);
}
Run Code Online (Sandbox Code Playgroud)
但是无法在JS中弄明白.
与 PHP 不同,如果对象不存在,您必须创建它们:
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
ar = [{"id":"15","heading":"Post1","content":"Post 1 Content","date":"2016-11-09 08:51:37"},
{"id":"16","heading":"Post2","content":"Post 2 Content","date":"2016-11-09 08:52:09"},
{"id":"17","heading":"Post3","content":"Post 3 Content","date":"2015-06-09 08:52:09"}]
obj = {}
ar.forEach(function(v) {
d = new Date(v.date);
m = monthNames[d.getMonth()]
if (!obj.hasOwnProperty(d.getFullYear())) {
obj[d.getFullYear()] = {}
}
if (!obj[d.getFullYear()].hasOwnProperty(m)) {
obj[d.getFullYear()][m] = []
}
obj[d.getFullYear()][m].push(v.heading)
})
console.log(obj)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
93 次 |
| 最近记录: |