0

我需要一些帮助来遍历我从 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);
}
4

3 回答 3

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
}
于 2012-11-28T18:26:42.803 回答
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);
                });
            });

我希望这可以帮助任何需要类似解决方案的人。

于 2012-11-29T12:22:17.690 回答
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]
于 2012-11-28T18:35:32.973 回答