2017-08-08 35 views
0

因此,我使用Azure Application Insights REST API從我的Web應用程序獲取數據,將其構建到圖形中以顯示在儀表板上。js/reactjs - 我如何從json重建數據到數組中?

即回來如下的JSON:

{ 
    "value": { 
    "start": "2017-08-07T23:01:50.847Z", 
    "end": "2017-08-08T11:01:50.847Z", 
    "interval": "PT1H", 
    "segments": [ 
     { 
     "start": "2017-08-07T23:01:50.847Z", 
     "end": "2017-08-08T00:00:00.000Z", 
     "requests/count": { 
      "sum": 317 
     } 
     }, 
     { 
     "start": "2017-08-08T00:00:00.000Z", 
     "end": "2017-08-08T01:00:00.000Z", 
     "requests/count": { 
      "sum": 332 
     } 
     }, 
     { 
     "start": "2017-08-08T01:00:00.000Z", 
     "end": "2017-08-08T02:00:00.000Z", 
     "requests/count": { 
      "sum": 337 
     } 
     }, 
     { 
     "start": "2017-08-08T02:00:00.000Z", 
     "end": "2017-08-08T03:00:00.000Z", 
     "requests/count": { 
      "sum": 326 
     } 
     } 
    ] 
    } 
} 

我需要得到在「段」「結束」「總和」值來構建的陣列,像這樣由於圖形API需要陣列是在以下格式:

[ 
    ["2017-08-08T00:00:00.000Z", 317], 
    ["2017-08-08T01:00:00.000Z", 332], 
    ["2017-08-08T02:00:00.000Z", 337], 
    ["2017-08-08T03:00:00.000Z", 326] 

]

我該如何做到這一點?

回答

0
var myArray = resultFromAPI.value.segments.map(function(segment) { 
    return [segment.end, segment["requests/count"].sum]; 
}); 

應該做的伎倆

0

使用JavaScript map。喜歡的東西:

t.value.segments.map(function(x) { return [ x.start, x['requests/count'].sum] })

1

如果你喜歡一些現代的JavaScript,你也可以這樣做:

// 「res」 is your API response 
const newArray = res.value.segments.reduce((acc, val) => { 
    return [...acc, [val.end, val['requests/count'].sum]]; 
}, []); 

瞭解更多關於reduce magic

我希望它能幫上忙!