Vinod
Vinod

Reputation: 32911

Modify JSON with typescript

I am creating a Angular 2 application. My server side request returns me a JSON that will look like

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

I need to display this in a dropdown. So I need to create a new JSON that will look like

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

I dont want to write for loop as i will be using this in many places and i want it to be best possible in performance. Please let me know if there is any inbuilt function that can do this kind of JSON restructure.

Upvotes: 2

Views: 14549

Answers (2)

user663031
user663031

Reputation:

Using ES6 destructuring, the most compact form would be:

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

Upvotes: 3

martriay
martriay

Reputation: 5742

Unless you know exactly how many elements there will be in your response array you can't escape from iterating it, although you can choose how:

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

Upvotes: 6

Related Questions