-5

Problem

I have the following example json data which is not formatted how I need it:

"stations": {
    "st1": "station 1",
    "st2": "station 2",
    "st3": "Station 3",
}

Question

How can I reformat the data to be:

"stations": [
  {
    "id": "st1",
    "name": "station 1",
  },
  {
    "id": "st2",
    "name": "station 2",
  },
  {
    "id": "st3",
    "name": "station 3",
  }
]

Tried

I tried to simply log the data to test first but am struggling how to actually even iterate between the key/value pairs as they are essentially strings

This is what i tried:

$.get( '/js/ajax/tube-data.json', function( data ) {

    $.each(data.stations, function () {
        // I was expecting st1, st2, st3 to show in the console
        // but got first letter of each station 
        console.log(this[0]) 
    });

}).error(function() {console.log(arguments) });

Is there a better way to do this?

StudioTime
  • 22,603
  • 38
  • 120
  • 207
  • 1
    Have you checked [the documentation for `$.each()`](http://api.jquery.com/jQuery.each/)? – JJJ Mar 11 '16 at 11:23
  • 1
    [`var arr = []; Object.keys(obj.stations).forEach(function(key) { arr.push({ id: key, name: obj.stations[key] }); });`](https://jsfiddle.net/tusharj/6dfoz1sp/) – Tushar Mar 11 '16 at 11:23

2 Answers2

2

Array#map() will do.

var object = { stations: { st1: "station 1", st2: "station 2", st3: "Station 3", } };

object.stations = Object.keys(object.stations).map(function (k) {
    return { id: k, name: object.stations[k] };
})

document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

I hope this helps. Its a plain vanilla code for doing the same:

var b=[];
for(key in a) {
    console.info(key);
    var x = {};
    x[key] = a[key];
    b.push(x);
}
console.info("b: ", b);
invincibleDudess
  • 1,762
  • 2
  • 11
  • 18