JSON Dynamic and Popular Datatable

Asked

Viewed 104 times

0

I’m having trouble generating a dynamically popular JSON message a Datatable.

When I do it this way it works:

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 doesn’t 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);

Generated msgJson message:

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

Some light?

  • I think the syntax like this p = "["" + (i+1)... can cause problem. Write distinguishing double quotes and simple like this p = '[""+ (i+1)...

2 answers

0


Instead of creating a string and then turning it into arrray, 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)
  }
  • var dataset = []; for (var i = 0; i < data.length - 1; i++){ var p = String(i+1); var d = String(data[i]); var v = String(vlr) var item = [p, d, v]; dataset.push(item) } thanks for the help, but as a game for datatable?

0

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.