如何修改/重新转换JSON数组结构 [英] How to modify/retransform JSON array structure

查看:90
本文介绍了如何修改/重新转换JSON数组结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  [{id:15,heading:Post1,content:发布1内容,日期: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
6月
Post3

我能够实现这在PHP中由

 而($ 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) 


[{"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.

解决方案

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)

这篇关于如何修改/重新转换JSON数组结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆