4

Sample code

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"}];

I have to get output something like above, have to add dynamically columns and its value to mydata.

I am trying to do something like this but its not working for me.

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);
}

above code doesnt works for me. any other way for it

2 Answers 2

5

Easy:

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
Sign up to request clarification or add additional context in comments.

Comments

5

Hope this can help you:

var json = []; 

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

// add an field 'b'
json['b'] = []; // another json object
...

in your case:

mydata=[];

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

3 Comments

thanks Soony, but I did not follow how the above will work. I have to add "a" or "b" or "c" and its value dynamically to json
are you suggesting me to do something like this
for (var r = 0; r < dataTable.getNumberOfRows(); r++) { for (var c = 0; c < dataTable.getNumberOfColumns(); c++) { mydata[dataTable.getColumnLabel(c)] = dataTable.getValue(r, c); } } It didnt worked out as I need output some thing like this. 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"} ];`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.