Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add data dynamically in JSON object

Tags:

json

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

like image 587
Mayank Avatar asked Jan 17 '23 14:01

Mayank


1 Answers

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
like image 80
Tolo Palmer Avatar answered Jun 26 '23 17:06

Tolo Palmer