Creating an array in JavaScript from a 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 to create an array in javascript like this:
var dataSet=[
['Paul','Jake','null','Max'],
['Sam','Tina','Emily','Harwell'],
['Tom','Julie','null','Adi']
];
I tried the following code but it doesn't work. Can anyone please help?
$.getJSON("filename.json", function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(val);
});
// β¦
});
I am using this array for display purposes (using DataTables), so I want to create an array in this format. I am using dataSet array to display in DataTables like this:
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" }
]
} );
} );
+3
source to share
4 answers
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 = [];
for (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>
+1
source to share
One liner:
var dataSet = rawData.map(function(e){ return Object.keys(e).map(function(i){ return e[i]}); })
Output:
Output as JSON:
Method Explanation (from Javascript Reference)
-
The method
map()
creates a new array with the results of calling the provided function for each element in that array. -
The method
Object.keys()
returns an array of the specified object its own enumerated properties
0
source to share