highcharts java json,转换JSON数据到格式Highcharts“基本路线图

Using Javascript, I am trying to convert some JSON data into the format used in Highcharts' basic line chart.

What I have to start with:

originalArray = [

['valueA', 1],

['valueA', 0],

['valueB', 9],

['valueB', 9],

['valueB', 3],

['valueC', 11]

]

And what I'm trying to create using the above:

desiredArray = [{

name: 'valueA',

data: [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

}, {

name: 'valueB',

data: [0, 0, 0, 1, 0, 0, 0, 0, 0, 2, 0, 0]

}, {

name: 'valueC',

data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]

}]

For some additional context, the 0-11 in originalArray[i][1] references a month (0 = January), and the desiredArray is a list of unique names and a count of their occurrences by month.

So far, I can:

Convert the data into a new array of objects

For each unique name in originalArray

Create a new object in the desiredArray, and set the name attribute

Add a data attribute that contains an empty array

But then I run into trouble, and can't figure out how to:

Loop through the originalArray

If the name in the originalArray matches the name in the desiredArray

Increment a counter in the matching seriesArray[i].data array, using the value of originalArray[i][1] as the index (it always be 0-11).

So I'm asking:

What's a good way to iterate across my originalArray, match up unique values, and then act only on those matches to push to the desiredArray.

What's the best way to increment the counters in desiredArray[i].data

I'm open to using libraries, such as underscore.js. Have been trying to figure this out for a couple of days now, so pretty much anything goes within the bounds of Javascript.

解决方案

Updated with proper array initialization, now.

var max = originalArray.reduce(function(p,c){return Math.max(p,c[1]);},0);

var initSums = function(size) {

var arr = new Array(size);

for (var i=0;i

arr[i]=0;

return arr;

}

var map = originalArray.reduce(function(sums,val){

if (!sums.hasOwnProperty(val[0])) {

sums[val[0]] = initSums(max+1);

}

sums[val[0]][val[1]]++;

return sums;

},{});

var desiredArray = Object.keys(map).map(function(key) {

return {name: key, data: map[key]};

});

What we're doing here is a multi-step process:

Decide how big our arrays are going to need to be, by first scanning for the largest value in the original array.

Use an object to aggregate the counts (using Array.reduce()).

Transform the object and its properties into an array of name/data pair objects (using Array.map).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值