JSON dynamic and popular DataTable

0

I am having problems generating a JSON message dynamically and popularly a DataTable.

When I do it works as follows:

var dataSet = [
   [ “1”, “01/10/2018”, “200,00” ],
   [ “2”, “01/11/2018”, “250,00” ],
   [ “3”, “01/12/2018”, “350,00” ]
];

$(’#teste’).DataTable({
   //paging: false,
   //searching: false,
   retrieve: true,
   destroy: true,
   data: dataSet,
   columns: [
     { title: “id” },
     { title: “Data” },
     { title: “Valor” }
   ]
});

When I try to generate dynamically, it does not work.

for (var i = 0; i < dados.length - 1; i++){

   p = “[ “” + (i+1) + “”,”;
   d = “”" + dados[i] + “”,";
   v = “”" + vlr + “” ]";
   msgJson = msgJson + p + d + v + “,”;

}

dataSet = msgJson.substr(0,msgJson.length-1);

MsgJson message generated:

[ “1”,“11/10/2018”,“30” ],[ “2”,“11/11/2018”,“30” ],[ “3”,“11/12/2018”,“30” ]

Any light?

    
asked by anonymous 30.08.2018 / 21:07

2 answers

0

Instead of creating a string and then transforming it into arrray, better create an array and add the items.

  var dataSet = [];

  for (var i = 0; i < dados.length - 1; i++){
    var p = String(i+1);
    var d = String(dados[i]);
    var v = String(vlr)

    var item = [p, d, v];
    dataSet.push(item)
  }
    
30.08.2018 / 21:24
0

It worked!

      var dataSet = [];

      for (var i = 0; i < dados.length - 1; i++){
        var p = String(i+1);
        var d = String(dados[i]);
        var v = String(vlr)

        var item = [p, d, v];
        dataSet.push(item)
     }                                                 

     $('#tblParcelas').DataTable({
        //paging: false,
        //searching: false,
        //retrieve: true,           
        data: dataSet,
        columns: [
          { title: "Parcela" },
          { title: "Data Vencimento" },            
          { title: "Valor" }
          ]
     });    
    
30.08.2018 / 21:46