简体   繁体   中英

js/reactjs - How do i reconstruct data from a json into a array?

So i'm using Azure Application Insights REST API to get data from my web app to construct it into a graph to be displayed on a dashboard.

The json that comes back is as follows:

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

I need to get the "end" and "sum" values in "segments" to construct an array like so since the graph api requires the array to be in this format:

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

]

How can i achieve this?

If you prefer some modern JavaScript , you can also do something like :

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

Learn more about reduce magic .

I hope it will help !

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

should do the trick

Use javascript map . Something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM