0

I have a response from API where JSON is not in an array, something like below

{
  "TV": {
    "USD": 9677.25,
    "EUR": 7768.87,
    "JPY": 1072773.87,
    "GBP": 6898.93,
    "AUD": 12294.15,
    "CAD": 12056.19
},
 "Lamp": {
    "USD": 231.35,
    "EUR": 185.89,
    "JPY": 25735.85,
    "GBP": 168.82,
    "AUD": 296.7,
    "CAD": 283
  }
}

if it is array I can use .map function, but in this scenario how can I display data while looping it as data coming from API might be different on every call.

desired format that i am looking for is

[{
    "PRODUCT": "TV",
    "PRICE": {
        "USD": 9677.25,
        "EUR": 7768.87,
        "JPY": 1072773.87,
        "GBP": 6898.93,
        "AUD": 12294.15,
        "CAD": 12056.19
    }
}, {
    "PRODUCT": "Lamp",
    "PRICE": {
        "USD": 231.35,
        "EUR": 185.89,
        "JPY": 25735.85,
        "GBP": 168.82,
        "AUD": 296.7,
        "CAD": 283
    }
}]

Please help..

4
  • 1
    What is the desired output? Commented Feb 15, 2018 at 4:31
  • @HassanImam I want to convert above mention JSON to array Commented Feb 15, 2018 at 6:18
  • Please update the question with the desired format. Commented Feb 15, 2018 at 6:19
  • @HassanImam updated. Commented Feb 15, 2018 at 6:30

2 Answers 2

1

You can use Object.keys() to iterate through each key of your data and then using array#map, you can create a resultant array with your objects.

var data = { "TV": { "USD": 9677.25, "EUR": 7768.87, "JPY": 1072773.87, "GBP": 6898.93, "AUD": 12294.15, "CAD": 12056.19 }, "Lamp": { "USD": 231.35, "EUR": 185.89, "JPY": 25735.85, "GBP": 168.82, "AUD": 296.7, "CAD": 283 } },
  result = Object.keys(data).map(k => ({PRODUCT: k, PRICE: data[k]}));
console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

You can retrieve the keys for the top level properties of the JSON object.

var payload = {
  "TV": {
    "USD": 9677.25,
    "EUR": 7768.87,
    "JPY": 1072773.87,
    "GBP": 6898.93,
    "AUD": 12294.15,
    "CAD": 12056.19
},
 "Lamp": {
    "USD": 231.35,
    "EUR": 185.89,
    "JPY": 25735.85,
    "GBP": 168.82,
    "AUD": 296.7,
    "CAD": 283
  }
}

var keys = Object.keys(payload)

Now you can map over these keys and use them to reference the payload. So for example if you wanted to create an array with the USD cost of each item.

var usdCost = keys.map(function (key) {
  return {
    item: key,
    usd: payload[key].USD
  }
})

// [{
//   item: "TV",
//   usd: 9677.25
// }, {
//   item: "Lamp",
//   usd: 231.35
// }]

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.