我有一个json文件,其结构如下:
{
"won":3,
"lost":0,
"void":0,
"active":1
}
我一直在试图弄清楚如何在javascript中制作两个包含以下信息的数组:
var labels = ["won", "lost", "void", "active"];
var data = ["3","0", "0","1"];
但我无法理解如何做到这一点。
答案 0 :(得分:4)
您可以使用:
var labels = Object.keys(input);
var data = Object.values(input);
但是你应该检查浏览器的兼容性:
答案 1 :(得分:1)
试试此代码
var item_list = {
"won":3,
"lost":0,
"void":0,
"active":1
};
var labels = [];
var data = [];
for(var item in item_list){
// console.log(item);
labels.push(item);
data.push(item_list[item]);
}
console.log(labels);
console.log(data);
答案 2 :(得分:0)
你也可以这样做
var mydata = {
"won":3,
"lost":0,
"void":0,
"active":1
};
var first = [],
second = [];
for (var property in mydata) {
if ( ! mydata.hasOwnProperty(property)) {
continue;
}
first.push(property);
second.push(mydata[property]);
}
console.log(first);
console.log(second);

答案 3 :(得分:0)
使用for..in
,如下所示:
var obj = {
"won":3,
"lost":0,
"void":0,
"active":1
}
var labels = [];
var data = [];
for(key in obj){
labels.push(key);
data.push(obj[key])
}
console.log(labels)
console.log(data)

答案 4 :(得分:0)
试试这个:
var obj = {
"won":3,
"lost":0,
"void":0,
"active":1
}
var keys = new Array();
var values = new Array();
for (var key in obj) {
keys.push(key)
values.push(obj[key]);
}
console.log(keys);
console.log(values);