2014-06-11 39 views
0

我的目標是能夠產生完全像這樣的東西。jQuery .each()創建對象數組

var data = google.visualization.arrayToDataTable([ 
    ['Year', 'Cost'], 
    ['2004', 1000], 
    ['2005', 1170], 
    ['2006', 660], 
    ['2007', 1030] 
    ]); 

但我試圖得到它的使用由JSON

{ 
     "uid": 1, 
     "name": "Cost", 
     "data": [ 
      { 
       "year": 2009, 
       "cost": 640 
      }, 
      { 
       "year": 2010, 
       "cost": 620 
      }, 
      { 
       "year": 2011, 
       "cost": 600 
      }, 
     { 
      "year": 2012, 
      "cost": 620 
     } 
] 
} 

產生的數據,並通過使用這個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); 
}); 

但是我注意到的是,做它作爲一個字符串被推送,什麼是正確的方式來推送對象到一個數組,所以我可以得到這個工作。

+0

我不知道是什麼讓你把擺在首位的字符串。我的意思是,看起來你知道什麼是陣列,因爲你正在使用它們。 –

回答

4

.map會比.each更好。

$.getJSON("js/cost.json", function(d) { 
    var items = $.map(d.data, function(v) { 
    return [[v.year, v.cost]]; 
    }); 
}); 

The demo.

+0

@KingKing你是對的,我修復了代碼。但它可能會返回'[['年','成本'],...]'。 – xdazz

+0

我剛剛發現了這種方式,看看你已經修好了:) –

5

當前您正在創建一個字符串,然後推送到數組。的

items.push("['"+v.year+"',"+v.cost+"]"); 
3

使用

items.push([v.year, v.cost]); 

不是數據被推爲一個字符串,因爲你正在傳遞一個字符串items.push。如果你想要一個數組,只需按一個數組:

items.push([v.year, v.cost]); 

這就是你需要做的。
通過對事物的外觀,不過,你希望今年是一個字符串,而不是一個數字,看到你引用的v.year值:

items.push("['" + v.year + "', " + v.cost + "]"); 

要做到這一點,只需使用JS的類型脅迫:

items.push([''+v.year, +(v.cost)]); 
//concatenate with empty string => coerce to string 
// +(someValue) coerces someValue to number