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 :
And what i'd like to get is :
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?
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(var 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.
You can use map
to change objects to arrays and also Object.keys
and map
to return only object values.
var data = [{"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 result = data.map(function(e) { return Object.keys(e).map(function(k) { return e[k] }) }) console.log(result)
Or with ES6 you can use arrow functions like this
var result = data.map(e => Object.keys(e).map(k => e[k]))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.