unkn0wn unkn0wn - 26 days ago 11
Javascript Question

How to modify/retransform JSON array structure

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


I have above JSON array. I am trying to convert it into a JSON Object as

2016
Nov
Post1
Post2
2015
June
Post3


I was able to achieve this in PHP by

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]);
}


But can't figure it out in JS.

Answer

Unlike PHP you must create the objects if they don't exists:

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)

Comments