2

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.

6
  • 2
    Are you sure you need to transform the JSON? Cannot the UI component be configured to use alternate keys for label and value? Commented Aug 21, 2016 at 3:10
  • 3
    A for loop is exactly what you need (although map() is nicer). Commented Aug 21, 2016 at 3:11
  • @Thilo I am using custom library primeng. This probably does not support for now. Commented Aug 21, 2016 at 3:16
  • Sometimes you just have to write some code darnit! Commented Aug 21, 2016 at 7:34
  • 1
    You don't really want to create new JSON. I assume you're converting the JSON resturned to a javascript array and want to convert the objects in the array to objects with different properties. Using JSON in your title and using the JSON tag makes it seem like you are talking about JSON in particular (JavaScript Object Notation), the string representation of javascript objects. Commented Aug 21, 2016 at 12:16

2 Answers 2

6

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']
  })
)
Sign up to request clarification or add additional context in comments.

3 Comments

... and it is very unlikely that any of this will cause any performance issues.
Yeap, don't worry, not with such a simple structure
Thank you very much. Let me give this a try.
3

Using ES6 destructuring, the most compact form would be:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.