2

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?

2
  • Post actual data here Commented Feb 5, 2017 at 15:47
  • I edited my question. Commented Feb 5, 2017 at 15:50

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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]))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.