1

我有一个从 php 进行 json 编码的数组

数组看起来像这样(称为 $jsonGraphData;):

[{"Type":"Category","Name":"games","TotalClicks":"162"},{"Type":"Category","Name":"apps","TotalClicks":"29"},{"Type":"Category","Name":"music","TotalClicks":"28"},{"Type":"Category","Name":"video","TotalClicks":"25"}]

我想在生成图形的 jquery 函数中的循环中使用数组值。这些是允许图表工作的硬编码值:

series: [{
                name: 'games',
                data: [162]

            }, {
                name: 'apps',
                data: [29]

            }, {
                name: 'video',
                data: [25]

            }]

我想做的是使用 jquery 'each' 循环遍历数组,以便定义系列是动态的,这就是我想要实现的:

var totalClicks = $jsonGraphData; (this is the array, the alert works fine).

series: [{
  $.each(totalClicks, function(index, val) {
    alert('name: ' + val.Name + ' ' + 'data: ' + val.TotalClicks);
    //here is where I need the format to be the same as the example above.
  });   
}]

我缺乏实现此目的的 jquery 语法知识,也不知道在 Google 上搜索什么。

4

2 回答 2

0

试试这个代码

var series = [];
  $.each(totalClicks, function(index, val) {
    series.push({name: val.Name, data: val.TotalClicks});
  });   

或者,如果数据仍然应该是一个只有一个值的数组。

var totalClicks = [{ "Type": "Category", "Name": "games", "TotalClicks": "162" }, { "Type": "Category", "Name": "apps", "TotalClicks": "29" }, { "Type": "Category", "Name": "music", "TotalClicks": "28" }, { "Type": "Category", "Name": "video", "TotalClicks": "25"}]

var series = [];
$(totalClicks).each(function (index, val) {
    series.push({ "name": val.Name, "data": [val.TotalClicks] });
});
于 2013-01-17T09:55:28.460 回答
0

您不需要使用 jQuery 来循环遍历常规数组。

for(var obj in yourArray){
  // do whatever you need with it.
  alert(obj.Name + " " + obj.TotalClicks);
}
于 2013-01-17T09:58:23.757 回答