gpt4 book ai didi

javascript - 从 JSON 文件在 JavaScript 中创建数组

转载 作者:行者123 更新时间:2023-11-29 15:33:42 24 4
gpt4 key购买 nike

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

最佳答案

你得到一个对象数组,你想要一个数组的数组,所以通过读取对象的属性将每个对象转换为数组:

var items = [];
$.each( data, function( key, val ) {
items.push([val.val0,val.val1,val.val2,val.val3]);
});

关于javascript - 从 JSON 文件在 JavaScript 中创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31885438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com