简体   繁体   中英

plot json data on html table using ajax response

this is the sample json:

[
  {
    "datetime": "2020-07-01T00:00:00",
    "params": [
      {
        "parameterName": "Temperature",
        "value": 20,
        "color": "Green"
      },
      {
        "parameterName": "PH Level",
        "value": 86,
        "color": "Green"
      },
      {
        "parameterName": "Partical Level",
        "value": 2,
        "color": "Green"
      },
      {
        "parameterName": "Oxygen Level",
        "value": 8897,
        "color": "Green"
      },
      {
        "parameterName": "Salinity",
        "value": 8849,
        "color": "Green"
      }
    ]
  },
  {
    "datetime": "2020-07-01T01:00:00",
    "params": [
      {
        "parameterName": "Temperature",
        "value": 21,
        "color": "Green"
      },
      {
        "parameterName": "PH Level",
        "value": 85,
        "color": "Green"
      },
      {
        "parameterName": "Partical Level",
        "value": 3,
        "color": "Green"
      },
      {
        "parameterName": "Oxygen Level",
        "value": 8895,
        "color": "Green"
      },
      {
        "parameterName": "Salinity",
        "value": 8847,
        "color": "Green"
      }
    ]
  }
]

now i need to convert this json to html data table which should be looking like this:

date                | Temperature | PH Level | Partical Level | Oxygen Level | Salinity
2020-07-01T00:00:00 | 20          | 86       | 2              | 8897         | 8849

search and other things are handled by javascript, what I need is the structure only where datetime will be row and column names will be the parameterName attribute. In one word the table should be looking like this

// these is used for changing params items to simple key value pair object
function simplify(obj){
    let newobj={} ;
    newobj[obj.parameterName] = obj.value;
    return newobj;
} 

// these use simplified key value pairs to make row object
function makeRow(obj) { 
     let newobj={datetime: JsonResponse.datetime} 
    
     // JsonResponse is your response
    JsonResponse.params.foreach(function(item) {
         newobj = { ...newobj, ...simplify(item) } ;
    } ) ;
    return newobj;
} 
// flattened object
let NewJson = JsonResponse.map(function(item){
     return makeRow(item) 
} ) ;

That concludes the hard part NewJson should be flattened object you can use that to fill table using javascript

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