Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]]];
like image 809
Michael Meier Avatar asked Mar 19 '13 20:03

Michael Meier


2 Answers

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);
    }
}
like image 139
jfriend00 Avatar answered Sep 23 '22 17:09

jfriend00


You could do something like this:

var chartData = []

for(var key in data) {        
    var properties = data[key];

    if(typeof properties === "object") {
       var array = [];

       for(var propKey in properties) {
           array.push([propKey, properties[propKey]])
       }

       chartData.push(array);
    }             
}

Check out the fiddle.

like image 44
Vivin Paliath Avatar answered Sep 23 '22 17:09

Vivin Paliath