Angular 从Typescript中的JSON响应对象获取单独的标题行和数据行
我正在从Angular 5进行API调用,响应格式如下Angular 从Typescript中的JSON响应对象获取单独的标题行和数据行,angular,typescript,Angular,Typescript,我正在从Angular 5进行API调用,响应格式如下 { "metadata":{ "lastSyncTime":"2000-11-21T16:07:53", "dataFromDB":true }, "allocationReports":[ { "allocatedUserCount":100,
{ "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
}
}
我需要实现一个下载功能,需要一个单独的格式,如一个标题行和一个数据行的数据。
因此,下载服务需要以下格式的数据
{ "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
}
}
标题行:[“吃得更健康”、“感觉更快乐”、“戒烟”]
数据行:[100130150]
我写的逻辑不正确。它正在创建6个不同的阵列。有人能帮我解释一下逻辑吗
提前感谢。这可以通过
map
功能轻松完成:
// assuming the response body is stored in a variable called `response`:
const headerRow = response.allocationReports.map(report => report.healthGoalName))
const dataRow = response.allocationReports.map(report => report.allocatedUserCount))
为了解决评论者对两次循环的担忧(如果可读性和时钟周期对您来说不重要,则为NBD),这里有一个优化版本:
const headerRow = [];
const dataRow = [];
response.forEach(report => {
headerRow.push(report.healthGoalName);
dataRow.push(report.allocatedUserCount);
});
你应该发布不起作用的逻辑,这样你不仅可以得到正确的答案,而且可以更好地理解哪里出了错。映射函数可以工作,但你必须循环一次标题,循环一次数据。一个一个更好,特别是如果列表比3大得多(虽然这似乎是聚合数据,它可能不会变得很大)@cjd82187这是一个常见的误解,即每一行的N个循环比每一行的1个循环慢得多。随着N的增长,两者之间的差异变得越来越小。如果您正在编写每个时钟周期都很重要的高性能代码,请务必尽可能地进行疯狂和优化。如果不是这样的话,即使使用1K+元素的数组,我的答案的可读性优势也远远超过您将获得的任何节省