gpt4 book ai didi

javascript - 如何修改/重新转换 JSON 数组结构

转载 作者:数据小太阳 更新时间:2023-10-29 06:00:25 25 4
gpt4 key购买 nike

[{"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"}]

我有上面的 JSON 数组。我正在尝试将其转换为 JSON 对象作为

2016
Nov
Post1
Post2
2015
June
Post3

我能够通过以下方式在 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]);
}

但无法在 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)

关于javascript - 如何修改/重新转换 JSON 数组结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40499946/

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