Robert Ross Robert Ross - 4 years ago 87
Javascript Question

How to convert a JSON object to array of arrays

In my application I am getting a json result from the controller, which I want to turn to array of arrays in the frontend, so I can work with the google charts api.

Currently I am using a

$.parseJSON(result)
on the string I am getting, so in the end i get this in the console :

enter image description here

And what i'd like to get is :

enter image description here

Here is the initial json string, which i get before the parseJSON part :

[{"rolename":"some role","perc":45.5},{"rolename":"another role","perc":36.4},{"rolename":"role three","perc":9.1},{"rolename":"role four","perc":9.1}]


Any tips on how can i achieve that?

Answer Source

ES6 ( quite new cool stuff ):

var json=[{"rolename":"some role","perc":45.5},{"rolename":"another role","perc":36.4},{"rolename":"role three","perc":9.1},{"rolename":"role four","perc":9.1}];

var answer=json.map(el=>Object.values(el));

Working: http://jsbin.com/pejucoriqu/edit?console

ES5 ( compatible with a lot browsers):

var answer=json.map(function(el){
 var arr=[];
for(key in el){
  arr.push(el[key]);
}
return arr;
});

Youve got an array of objects, And you want an array of arrays. So take each element and map it with the values of the object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download