【问题标题】:Transform an object to list of lists in typescript将对象转换为打字稿中的列表列表
【发布时间】:2020-11-02 00:24:12
【问题描述】:

我正在从 Angular 5 进行 API 调用,响应格式如下。

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

我需要将此数据转换为列表列表(或数组数组),以便我可以在此数据上绘制多个圆环图。我尝试了多种方法,例如使用 .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 } 
 ]
]

总注册值将来自overall.registeredCount

【问题讨论】:

    标签: javascript angular typescript angular6 angular5


    【解决方案1】:

    试试这个

    ob={"metadata":{ "lastSyncTime":"2000-11-21T16:07:53", "dataFromDB":true }, "allocationReports":[      { "allocatedUserCount":100, "healthGoalName":"Eat Healthier" }, { "allocatedUserCount":130, "healthGoalName":"Feel Happier" }, { "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 }]})
    
    console.log(r)

    【讨论】:

    • 还有一个问题,请帮忙。我们可以按“allocatedUserCount”的升序对结果数组进行排序吗?
    猜你喜欢
    • 2021-06-28
    • 1970-01-01
    • 2013-12-02
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 2020-12-15
    相关资源
    最近更新 更多