簡體   English   中英

使用 typescript 在 Angular5 中對 JSON 響應進行排序

[英]Sorting a JSON response in Angular5 using typescript

我正在從 Angular 5 發出 API 調用,響應格式如下。

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
   }
}

我需要將此數據轉換為列表列表(或數組數組),以便我可以在此數據上使用 plot 多個圓環圖。 我嘗試了多種方法,例如 using.map,但在單個列表中獲取所有值。 如何以以下格式構建數據。

要求的格式是:[數組應該排序。]

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

我寫了下面的代碼。

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

但是我得到的結果沒有排序。 我該如何排序。

試試這個,它會按升序對它們進行排序

 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM