Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 639
Mercurial Avatar asked Nov 09 '16 03:11

Mercurial


People also ask

What is a JSONArray?

JsonArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array. A JsonArray object can be created by reading JSON data from an input source or it can be built from scratch using an array builder object.

Can JSON have arrays?

Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.

Can JSON array have different types?

Arrays are used for ordered elements. In JSON, each element in an array may be of a different type.

How does a -- JSONArray need to be structured?

A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.


1 Answers

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)
like image 165
Dekel Avatar answered Sep 23 '22 13:09

Dekel