从json抓取特定值以放入数据数组

时间:2018-10-08 12:17:54

标签: javascript json

我正在尝试从JSON响应中获取某些数据位以放入数组中。这是我的JSON响应,我感兴趣的是每小时计数的“计数”,由页面“声明”或“登录”分隔。

{
   "report":{
      "type":"trended",
      "elements":[
         {
            "id":"page",
            "name":"Page"
         }
      ],
      "reportSuite":{
         "id":"retail",
         "name":"GlobPROD"
      },
      "period":"Wed.  3 Oct. 2018 - Fri.  5 Oct. 2018",
      "metrics":[
         {
            "id":"pageviews"
         }
      ],
      "segments":[
         {
            "id":"s13bb443734ab6a764639ff37",
            "name":"Information"
         }
      ],
      "data":[
         {
            "name":"Wed.  3 Oct. 2018",
            "year":2018,
            "month":10,
            "day":3,
            "hour":0,
            "breakdown":[
               {
                  "name":"CATEGORY:>Statement",
                  "url":"",
                  "counts":[
                     "242"
                  ]
               },
               {
                  "name":"CATEGORY:>Log On",
                  "url":"...CheckId.do",
                  "counts":[
                     "237"
                  ]
               }
            ],
            "breakdownTotal":[
               "2123"
            ]
         },
         {
            "name":"Wed.  3 Oct. 2018 (Hour 1)",
            "year":2018,
            "month":10,
            "day":3,
            "hour":1,
            "breakdown":[
               {
                  "name":"CATEGORY:>Statement",
                  "url":"",
                  "counts":[
                     "152"
                  ]
               },
               {
                  "name":"CATEGORY:>Log On",
                  "url":"",
                  "counts":[
                     "135"
                  ]
               }
            ],
            "breakdownTotal":[
               "1140"
            ]
         }

所以我要做的是首先能够在语句和登录之间拆分每小时数据,其次是每小时建立一个数据数组。

  

logindata:[237,135]

     

statementdata:[242,152]

我读到我可以尝试使用类似于以下内容的值:

 var t = JSON.parse('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');

但是如何创建一个小循环来获取我在示例中指定的所有值?

2 个答案:

答案 0 :(得分:2)

您可以在内部使用m_map.end()的{​​{1}}方法并构建一个对象,其中每个reduce是单独的属性。

forEach

答案 1 :(得分:1)

我认为(如果json结构始终相同),您可以这样做:

for( let item in json.report.data ){
  for( let subItem in item.breakdown ){
    if( subItem.name === "CATEGORY:>Statement" ){
      //do something with subItem.counts, the statement counts
    } else if( subItem.name === "CATEGORY:>Log On" ){
      //do something with subItem.counts, the logOn counts
    }
  }
}