简体   繁体   English

如何将JSON对象转换为数组数组

[英]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. 在我的应用程序中,我从控制器中获取了一个json结果,我想将其转换为前端中的数组数组,以便可以使用谷歌图表API。

Currently I am using a $.parseJSON(result) on the string I am getting, so in the end i get this in the console : 目前,我在获取的字符串上使用$.parseJSON(result) ,所以最后我在控制台中得到了:

在此处输入图片说明

And what i'd like to get is : 我想得到的是:

在此处输入图片说明

Here is the initial json string, which i get before the parseJSON part : 这是我在parseJSON部分之前获得的初始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}]

Any tips on how can i achieve that? 关于如何实现该目标的任何提示?

ES6 ( quite new cool stuff ): ES6(相当不错的新东西):

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 工作: http//jsbin.com/pejucoriqu/edit?console

ES5 ( compatible with a lot browsers): ES5(与许多浏览器兼容):

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. 您可以使用map将对象更改为数组,也可以将Object.keys更改为map ,仅将对象值返回。

 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 或者使用ES6,您可以使用像这样的箭头功能

var result = data.map(e => Object.keys(e).map(k => e[k]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM