2017-08-31 31 views
-1

如何将Json数据转换为Array。我不能做到这一点 ,我有JSON数据为:如何将Json转换为Array在javascript中为chart.js

var setdata = [{ 
 
\t "data": [{ 
 
\t   "month" : "January", 
 
\t   "name" : "Alex", 
 
    \t   "count" : 10 
 
\t }] 
 
\t }, 
 
\t { 
 
\t "data": [{ 
 
\t   "month" : "February", 
 
\t   "name" : "Alex", 
 
    \t   "count" : 20 
 
\t }, 
 
\t { \t 
 
\t "data": [{ 
 
\t   "month" : "February", 
 
\t   "name" : "John", 
 
    \t   "count" : 30 
 
\t }, 
 
\t { \t 
 
\t "data": [{ 
 
\t   "month" : "February", 
 
\t   "name" : "Mark", 
 
    \t   "count" : 40 
 
\t }] 
 
       }, 
 
\t { 
 
\t "data": [{ 
 
\t   "month" : "March", 
 
\t   "name" : "Alex", 
 
    \t   "count" : 10 
 
\t }, 
 
\t { \t 
 
\t   "month" : "March", 
 
\t   "name" : "John", 
 
    \t   "count" : 20 
 
\t }] 
 
\t } 
 
    ]

我要转换为数组:

var months = ["January", "February", "March"] 

var data =  [10, 0, 0], 
       [0, 20, 10], 
       [0, 30, 20], 
       [0, 40, 0] 

我想使用setData创建堆积图。 js,你能为我做这个吗?请帮帮我。 谢谢。

+0

为什么不能ü尝试对象ARRY? –

+0

如何做到这一点? – jane

+0

请检查这种格式。 https://jsfiddle.net/caravinden/zpzpbf85/。这将是更好的迭代和访问 –

回答

0

你可以试试这个

var data = [{"month":"January","name":"Alex","count":10},{"month":"February","name":"Alex","count":20},{"month":"February","name":"John","count":30},{"month":"February","name":"Mark","count":40},{"month":"March","name":"Alex","count":10},{"month":"March","name":"John","count":20}]; 
 

 
// TO FIND UNIQUE ARRAY 
 
var months = data.map(function(t){ return t.month}); 
 
uniqueMonths = months.filter(function(item, pos) { 
 
    return months.indexOf(item) == pos; 
 
}); 
 
console.log('UNIQUE MONTHS:- '+uniqueMonths); 
 

 
var names = data.map(function(t){ return t.name}); 
 
uniqueNames = names.filter(function(item, pos) { 
 
    return names.indexOf(item) == pos; 
 
}); 
 
console.log('UNIQUE NAMES:- '+uniqueNames); 
 
var countArr = {}; 
 
uniqueNames.forEach(function(d){ 
 
\t var arr = []; 
 
\t uniqueMonths.forEach(function(k){ 
 
\t \t arr.push(getValue(d,k)); 
 
\t }); 
 
\t countArr[d] = arr; 
 
}); 
 
console.log('COUNT ARRAY:- '+JSON.stringify(countArr)); 
 

 
// To get value from the array 
 
function getValue(name, month){ 
 
\t var value = 0; 
 
\t data.forEach(function(d){ 
 
\t \t if(d.name == name && d.month == month){ 
 
\t \t \t value = d.count; 
 
\t \t } 
 
\t }); 
 
\t return value; 
 
}

+0

谢谢。但如何从[[10,20,10],[0,30,20],[0,40,0]] => [10,20,10],[0,30,20],[ 0,40,0]因为我创建了图表,它不显示图表。 – jane

+0

请检查以上更新的代码段 –

+0

谢谢。它可以堆积条形图吗?我不确定它是正确的吗? – jane

相关问题