Umar Adil
Umar Adil

Reputation: 5277

Convert multidimensional JSON to multidimensional JavaScript array

I receive from the server a JSON like the following:

{"sent":{"Executive":1},"received":{"Executive":1},"viewed":{"Executive":1}}

how to convert this structure to a JavaScript multidimensional array?

I would want something like this:

var sent = [["Executive", 1]];

var received = [["Executive", 1]];

var viewed = [["Executive", 1]];

Upvotes: 0

Views: 81

Answers (2)

Umar Adil
Umar Adil

Reputation: 5277

var plotdata = []; 
            var scale = [];
            var color = new Array();
            color[0] = "#3983C2";
            color[1] = "#F79263";
            color[2] = "#CB6FD7";
            color[3] = "#87B87F";
            color[4] = "#9ABC32";
            color[5] = "#D53F40";
            color[6] = "#999999";

            var x = 0;
            for(var i in json_data) {       
                var obj = json_data[i];
                var d1 = [];            
                for(var k in obj) {
                    d1.push([k, obj [k]]);  
                    scale.push([obj [k]]);      
                }
                x++;
                plotdata.push({ color: color[x], label: i, data: d1});
            }

Upvotes: 0

poitroae
poitroae

Reputation: 21377

The simplest and most dynamic way surely is a good old for-loop. Javascript doesn't ship with built-ins making this task easier.

An example of a 1d-array. I leave it open to the thread creator to add another, inner for-loop.

var json_data = {"sent": 1, "received": 2};
var result = [];

for(var i in json_data)
    result.push([i, json_data [i]]);

Upvotes: 1

Related Questions