javascript - 使用 typescript 修改 JSON
我正在创建一个 Angular 2 应用程序。我的服务器端请求返回给我的 JSON 看起来像
[{"CountryId":1,"CountryCode":"IND","CountryName":"India","State":[]},
{"CountryId":2,"CountryCode":"AUS","CountryName":"Australia","State":[]}]
我需要在下拉菜单中显示这个。所以我需要创建一个看起来像这样的新 JSON
[{"Label":"India","Value":"IND"},
{"Label":"Australia","Value":"AUS"}]
我不想写 for 循环,因为我会在很多地方使用它,并且我希望它在性能上尽可能最佳。请让我知道是否有任何内置函数可以完成这种 JSON 重构。
答案#1
除非你确切知道响应数组中会有多少元素,否则你无法避免遍历它,尽管你可以选择遍历的方式:
// A
let result = response.map((elem) => ({
'Label': elem.CountryName,
'Value': elem.CountryCode
}))
// B
let result = []
response.forEach((elem) =>
result.push({
'Label': elem.CountryName,
'Value': elem.CountryCode
})
)
// C
let result = []
for (i in response) {
result.push({
'Label': response[i]['CountryName'],
'Value': response[i]['CountryCode']
})
)
答案#2
使用 ES6 解构,最简洁的形式是:
response.map(({CountryCode: Label, CountryName: Value}) => ({Label, Value}))
