Vinodtiru Vinodtiru - 3 months ago 14
TypeScript Question

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.

Answer

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