Creating an array in JavaScript from JSON file -
my json file:
[{"val0":"paul","val1":"jake","val2":null,"val3":"max"}, {"val0":"sam","val1":"tina","val2":"emily","val3":"hardwell"}, {"val0":"tom","val1":"julie","val2":null,"val3":"adi"}]
i want create array in javascript follows:
var dataset=[ ['paul','jake','null','max'], ['sam','tina','emily','harwell'], ['tom','julie','null','adi'] ];
i tried following code isn’t working. can please help?
$.getjson("filename.json", function(data) { var items = []; $.each(data, function(key, val) { items.push(val); }); // … });
i’m using array display purpose (using datatables), so, want create array in format.i'm using dataset array displaying in datatables follows:
var dataset = [ ['paul','jake','isha','mike','null','null','parth','tinker'], ['tina','michael','null','blue','red','','emily','mina'] ]; $(document).ready(function() { $('#demo').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' ); $('#example').datatable( { "data": dataset, "columns": [ { "title": "name" }, { "title": "deadline" }, { "title": "additional fees" }, { "title": "requirements" }, { "title": "field" }, { "title": "award" }, { "title": "renewable requirements"}, { "title": "link" } ] } ); } );
a solution without jquery:
var data = [ { "val0": "paul", "val1": "jake", "val2": null, "val3": "max" }, { "val0": "sam", "val1": "tina", "val2": "emily", "val3": "hardwell" }, { "val0": "tom", "val1": "julie", "val2": null, "val3": "adi" } ], dataset = data.reduce(function (r, a) { var i, a0 = []; (i in a) { a0.push(a[i]); } r.push(a0); return r; }, []); document.getelementbyid('out').innerhtml = json.stringify(dataset, null, 4);
<pre id="out"></pre>
Comments
Post a Comment