简体   繁体   中英

Sorting a JSON response in Angular5 using typescript

I am making an API call from Angular 5, the response is coming in below format.

let ob = {   "metadata":{
      "lastSyncTime":"2000-11-21T16:07:53",
      "dataFromDB":true
   },
   "allocationReports":[ 
      {
         "allocatedUserCount":130,
         "healthGoalName":"Feel Happier"
      },
  
      {
         "allocatedUserCount":150,
         "healthGoalName":"Quit Smoking"
      },
      {
         "allocatedUserCount":100,
         "healthGoalName":"Eat Healthier"
      }
   ],
   "overall":{
      "usersWithGoalCount":0,
      "registeredCount":500,
      "eligibleCount":280
   }
}

I need to transform this data into a list of lists(or Array of Arrays) so that I can plot multiple donut charts on this data. I have tried with multiple methods like using.map, but getting all the values in single list. How can I build the data in below format.

The required format is: [Array should be sorted.]

[ 
 [
  { "x": "Eat Healthier", "y": 100 },
  { "x": "Total registered", "y": 500 } 
 ],
 [
  { "x": "Feel Happier", "y": 130 },
  { "x": "Total registered", "y": 500 } 
 ],
 [
  { "x": "Quit Smoking", "y": 150 },
  { "x": "Total registered", "y": 500 } 
 ]
]

I have written below code.

r=ob.allocationReports.map(o=>{return [{x:o.healthGoalName,y:o.allocatedUserCount},{x: "Total registered", y: ob.overall.registeredCount }]})

But the result I am getting is not sorted. How can I sort this.

Try this it will sort them in ascending order

 ob={"metadata":{ "lastSyncTime":"2000-11-21T16:07:53", "dataFromDB":true }, "allocationReports":[ { "allocatedUserCount":130, "healthGoalName":"Feel Happier" }, { "allocatedUserCount":100, "healthGoalName":"Eat Healthier" },{ "allocatedUserCount":150, "healthGoalName":"Quit Smoking" } ], "overall":{ "usersWithGoalCount":0, "registeredCount":500, "eligibleCount":280 } } r=ob.allocationReports.map(o=>{return [{x:o.healthGoalName,y:o.allocatedUserCount},{x: "Total registered", y: ob.overall.registeredCount }]}).sort((a,b)=>a[0].yb[0].y) console.log(r)

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