我有一个已经从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上搜索什么。
答案 0 :(得分: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] });
});
答案 1 :(得分:0)
您不需要使用jQuery循环遍历常规数组。
for(var obj in yourArray){
// do whatever you need with it.
alert(obj.Name + " " + obj.TotalClicks);
}