Search code examples
javascriptjsonelementparent-childparent

javascript json create parent element for each current element


I've got the following JSON:

{
  "BTC": "0",
  "XCP": "0",
  "NOBL": "0",
  "USDE": "0",
  "SOC": "0",
  "KDC": "0",
  "DOGE": "0.00000001"
}

What i need to obtain is:

[
 { "Coin": "BTC",
    "Value": "0"
 },
 { "Coin": "XCP",
    "Value": "0"
 },
 { "Coin": "NOBL",
    "Value": "0"
 },
 { "Coin": "USDE",
    "Value": "0"
 },
 { "Coin": "SOC",
    "Value": "0"
 },
 { "Coin": "KDC",
    "Value": "0"
 },
 { "Coin": "DOGE",
    "Value": "0.00000001"
 }
]

I don't know exactly how to achieve this...i suppose i need to use a foreach key function but i don´t know exactly how to solve this... Regards,


Solution

  • You can use a "for (var x in y)" type of loop to enumerate through the source collection:

    var source = {
      "BTC": "0",
      "XCP": "0",
      "NOBL": "0",
      "USDE": "0",
      "SOC": "0",
      "KDC": "0",
      "DOGE": "0.00000001"
    };
    
    var destination = [];
    
    for (var type in source) {
        destination.push({
            Coin: type,
            Value: source[type]
        });
    }