2016-08-21 34 views
0

我正在创建一个Angular 2应用程序。我的服务器端请求返回给我一个JSON,看起来像用typescript修改JSON

[{"CountryId":1,"CountryCode":"IND","CountryName":"India","State":[]}, 
{"CountryId":2,"CountryCode":"AUS","CountryName":"Australia","State":[]}] 

我需要在下拉菜单中显示它。所以,我需要创建一个新的JSON看起来像

[{"Label":"India","Value":"IND"}, 
{"Label":"Australia","Value":"AUS"}] 

我不想写一个循环,我会在很多地方使用这一点,我想这是最好的性能。请让我知道是否有任何可以做这种JSON重构的内置函数。

+2

您确定需要转换JSON吗?无法将UI组件配置为使用替代键作为标签和值? – Thilo

+3

'for'循环正是你所需要的(虽然map()更好)。 – SLaks

+0

@Thilo我正在使用自定义库[primeng](http://www.primefaces.org/primeng/#/dropdown)。这可能现在不支持。 – Vinodtiru

回答

3

除非你确切地知道有多少元素会在你的反应阵列无法从迭代逃避它,尽管你可以选择如何:

// 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'] 
    }) 
) 
+3

......并且这很可能不会导致任何性能问题。 – Thilo

+0

Yeap,别担心,不要用这么简单的结构 – martriay

+0

非常感谢。让我试试这个。 – Vinodtiru

3

使用ES6解构,最紧凑的形式是:

response.map(({CountryCode: Label, CountryName: Value}) => ({Label, Value}))