[英]jQuery .each() creating object array
My goal is to be able to generate something exactly like this. 我的目标是能够生成完全像这样的东西。
var data = google.visualization.arrayToDataTable([
['Year', 'Cost'],
['2004', 1000],
['2005', 1170],
['2006', 660],
['2007', 1030]
]);
But I am trying to get it done by using data that is generated by JSON 但是我试图通过使用JSON生成的数据来完成它
{
"uid": 1,
"name": "Cost",
"data": [
{
"year": 2009,
"cost": 640
},
{
"year": 2010,
"cost": 620
},
{
"year": 2011,
"cost": 600
},
{
"year": 2012,
"cost": 620
}
]
}
And by using this jQuery 并通过使用此jQuery
$.getJSON("js/cost.json", function(d) {
console.log(d.data);
var items = [];
$.each( d.data, function( k, v ) {
console.log(v.cost);
console.log(v.year);
items.push("['"+v.year+"',"+v.cost+"]");
});
console.log(items);
});
But what I'm noticing is that its being pushed as a string, what is the correct way to push objects to an array so I can get this working. 但是我要注意的是将其作为字符串推送,将对象推送到数组的正确方法是什么,这样我才能使它正常工作。
Currently your are creating a string and then pushing to array. 当前,您正在创建一个字符串,然后推送到数组。
Use 采用
items.push([v.year, v.cost]);
instead of 代替
items.push("['"+v.year+"',"+v.cost+"]");
The data is being pushed as a string, because you are passing a string to items.push
. 数据将作为字符串推送,因为您正在将字符串传递给
items.push
。 If you want an array, simply push an array: 如果需要数组,只需推送一个数组:
items.push([v.year, v.cost]);
That's all you need to do. 这就是您需要做的。
By the looks of things, though, you want the year to be a string, and not a number, seeing as you're quoting the value of v.year
: 从外观
v.year
,您希望year为字符串,而不是数字,因为您引用的是v.year
的值:
items.push("['" + v.year + "', " + v.cost + "]");
To do that, simply use JS's type coercion: 为此,只需使用JS的类型强制:
items.push([''+v.year, +(v.cost)]);
//concatenate with empty string => coerce to string
// +(someValue) coerces someValue to number
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.