我需要一些帮助来循环遍历我从API接收的JSON对象,并为图表库组装另一个对象。
以下是该对象的示例:
var channel_data = [
{
"27th Oct 12": {
"xaxis": "27th Oct 12",
"channels": {
"Create and Craft": {
"views": 13064,
"bandwidth": 623136899214,
"name": "Create and Craft"
},
"5 USA": {
"views": 394,
"bandwidth": 17889861768,
"name": "5 USA"
}
},
"totalViews": 25470,
"totalBandwidth": 923866774348
},
"28th Oct 12": {
"xaxis": "28th Oct 12",
"channels": {
"Create and Craft": {
"views": 15298,
"bandwidth": 860108829822,
"name": "Create and Craft"
},
"5 USA": {
"views": 500,
"bandwidth": 28770314737,
"name": "5 USA"
}
},
"totalViews": 29377,
"totalBandwidth": 1248778079465
}
}
]
我需要遍历这些数据并构建以下对象数组以用于Highcharts渲染。类别将是日期,数据是每个频道的每个日期的视图。
categories: ['27th Oct 12", "28th Oct 12"]
series: [{
name: 'Create and Craft',
data: [13064, 15298]
}, {
name: '5 USA',
data: [394, 500]
}, {
}]
我尝试了以下操作,但最终得到了错误的结构;
var dates = [], channels=[], views = [];
for (var gdata in channel_data) {
dates.push(channel_data[gdata].xaxis);
for (var channel in channel_data[gdata].channels){
channel_name = channel_data[gdata].channels[channel].name;
channel_views = channel_data[gdata].channels[channel].views;
channel_data = {"name" :channel_name,"views" : channel_views}
channels.push(channel_data);
}
views.push(model.attributes[gdata].channels.name.views);
}
答案 0 :(得分:0)
您可以使用此
var categories = [];
var series = [];
for(var i in channel_data) {
categories.push(channel_data[i].xaxis); //your categories
//same logic to loop through channels to populate series array
}
答案 1 :(得分:0)
您正在尝试将数据结构缩减为另一种形式。
这可以通过_js(下划线js)
之类的辅助工具来实现http://underscorejs.org/#reduce
从他们的网站逐字逐句采取的例子
var list = [[0, 1], [2, 3], [4, 5]];
var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
=> [4, 5, 2, 3, 0, 1]
答案 2 :(得分:0)
在一天结束时使用的解决方案,在AlanH的想法的帮助下使用下划线。
var channels = {};
_.each(channel_data, function( date, i ) {
_.each(date.channels, function( channel, i ) {
if ( channels[channel.name] === undefined ) {
channels[channel.name] = {
name : channel.name,
views : [],
bandwidth : []
};
}
channels[channel.name].views.push(channel.views);
channels[channel.name].bandwidth.push(channel.bandwidth);
});
});
我希望这有助于任何需要类似解决方案的人。