2012-02-03 69 views
2

示例代碼如何動態地在JSON對象

var mydata = [ {id:"1",invdate:"2007-10-01",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"}, {id:"2",invdate:"2007-10-02",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"}]; 

我得輸出類似上面,必須動態地添加列並將其值改爲MYDATA添加數據。

我想要做這樣的事情,但它不適合我。

var mydata = []; 
for (var r = 0; r < dataTable.getNumberOfRows(); r++) { 
    var items = ""; 
    var y =""; 
    for (var c = 0; c < dataTable.getNumberOfColumns(); c++) { 
    items += '"'+dataTable.getColumnLabel(c)+'":'+dataTable.getValue(r, c) 
     if(c!=dataTable.getNumberOfColumns()-1){ 
     items += ","; 
     } 
    } 
    y = "{"+items+"}"; 
    mydata.push(y); 
} 

上面的代碼不適用於我。任何其他方式爲它

回答

4

簡單:

oldJsonObj.vector = [] //this creates a new element into the object

foreach(dataTable.getNumberOfRows()){ 
    var x = {} 
    x.id = XXX; 
    x.name = XXX; 
    oldJsonObj.vector.push(x); //adds the element x to array 
} 

alert(oldJsonObj.vector[i].name); //easy accses 
3

希望這可以幫助你:

var json = []; 

// add an field 'a' 
json['a'] = 1; 
alert(json["a"]); //1 

// add an field 'b' 
json['b'] = []; // another json object 
... 
你的情況

mydata=[]; 

// add json fields 
mydata["id"] = 1; 
mydata["invdate"] = "2007-10-01"; 
mydata["name"] = "test"; 
//... 
+0

感謝的Soony,但我沒有遵循如何abo ve會工作。 (var r = 0; r Mayank 2012-02-03 07:52:01

+0

中是否建議我這樣做 – Mayank 2012-02-03 08:34:19

+0

' (var c = 0; c Mayank 2012-02-03 08:38:24