繁体   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