Michael Meier Michael Meier - 2 months ago 12
JSON Question

Convert one javascript nested object data structure to nested arrays

I am trying to convert a JSON string in a Javascript object literal. I think it is possible with some loops, but i couldn't get it done. The target structure is shown below, "chartData".

Fiddle can be found here: http://jsbin.com/ajemih/13/edit

Here's the JSON data:

{
"1b":{
"allLoad":"130",
"loadMovement":"111",
"allMovement":"111"
},
"1a":{
"allLoad":"910",
"loadMovement":"671",
"allMovement":"280"
},
"systemLoad":"963"
}


This should it look like after the conversion:

chartData = [[['loadMovement', 111],
['allMovement', 120],
['allLoad', 130]],
[['Load+Move', 671],
['allMovement', 280],
['allLoad', 910]]];

Answer

I think this would work:

Working demo: http://jsfiddle.net/jfriend00/YmjDR/

var data = {
   "1b":{
      "allLoad":"130",
      "loadMovement":"111",
      "allMovement":"111"
   },
   "1a":{
      "allLoad":"910",
      "loadMovement":"671",
      "allMovement":"280"
   },
   "systemLoad":"963"
};

var chartData = [];

for (var i in data) {
    var item = data[i];
    var outer = [];
    // skip over items in the outer object that aren't nested objects themselves
    if (typeof item === "object") {
        for (var j in item) {
            var temp = [];
            temp.push(j);
            temp.push(item[j]);
            outer.push(temp);
        }
    }
    if (outer.length) {
        chartData.push(outer);
    }
}