我发现的所有与此相关的问题都是关于组合 JSON 对象和/或字符串。我正在使用一个名为“Fuse”的 jQuery 插件来搜索文件的内容(此处的 repo :https://github.com/krisk/Fuse)。这是我到目前为止的代码。
$.getJSON("data/bn1.json", function(data) {
start(data);
});
$.getJSON("data/bn2.json", function(data2) {
start(data2);
});
两个 JSON 文件看起来像这样(为简洁起见缩短):
[
{
"number": "001",
"name": "Cannon",
"rarity": "*",
"damage": "40",
"element": "Normal",
"description": "A nice, big Cannon!"
},
{
"number": "002",
"name": "HiCannon",
"rarity": "**",
"damage": "80",
"element": "Normal",
"description": "A nice, big Cannon!"
},
{
"number": "003",
"name": "M-Cannon",
"rarity": "***",
"damage": "120",
"element": "Normal",
"description": "A nice, big Cannon!"
}
]
要调用的最后一个 JSON 文件(在本例中为 bn2.json
)是我搜索时显示的文件。我想搜索两个以上的文件(将来会是六个文件)。我的项目的完整 JS 文件在这里:https://github.com/IdeasNeverCease/Gingnet/blob/master/scripts/gingnet.js (您也可以在那里找到我的 JSON 文件)。
如果有人能指出正确的方向,我将不胜感激。
最佳答案
您的问题归结为“我如何合并数组?”您可以使用 Array.concat() .
var allData = [];
$.getJSON("data/bn1.json", function(data) {
allData = allData.concat(data);
});
$.getJSON("data/bn2.json", function(data2) {
allData = allData.concat(data);
});
因为你有多个文件,最好是 use promises to wrap these all up和 handle them all at once .未经测试,但这应该可以帮助您入门:
var urls = [
'data/bn1.json',
'data/bn2.json',
'data/bn3.json'
// etc.
];
var deferreds = [];
$.each(urls, function (index, url) {
deferreds.push($.getJSON(url)); // Request all data simultaneously
});
$.when.apply($, deferreds).then(function () { // We have all data, merge it
var data = [];
$.each(arguments, function (index, chunk) {
data = data.concat(chunk);
});
start(data); // Do whatever you want to this new collection of data
});
关于javascript - 合并 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26748032/