我的JSON文件:
[{"val0":"Paul","val1":"Jake","val2":null,"val3":"Max"},
{"val0":"Sam","val1":"Tina","val2":"Emily","val3":"Hardwell"},
{"val0":"Tom","val1":"Julie","val2":null,"val3":"Adi"}]
我想在javascript中创建一个数组,如下所示:
var dataSet=[
['Paul','Jake','null','Max'],
['Sam','Tina','Emily','Harwell'],
['Tom','Julie','null','Adi']
];
我尝试了以下代码,但它无效。有人可以帮忙吗?
$.getJSON("filename.json", function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(val);
});
// …
});
我正在使用这个数组用于显示目的(使用DataTables),因此,我想以该格式创建数组。我使用dataSet数组在DataTables中显示如下:
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" }
]
} );
} );
答案 0 :(得分:1)
没有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 :(得分:0)
你得到一个对象数组,并且你想要一个数组数组,所以通过读取对象的属性将每个对象转换为数组:
var items = [];
$.each( data, function( key, val ) {
items.push([val.val0,val.val1,val.val2,val.val3]);
});
答案 2 :(得分:0)
试试这个
<script>
$(function() {
$.getJSON("filename.json", function(data) {
var items = [];
$.each(data, function(key, val) {
var tmp = [];
for (var Key in val) {
tmp.push(val[Key]);
}
items.push(tmp);
});
console.log(items);
});
});
答案 3 :(得分:0)