结合JSON文件?

时间:2014-11-05 01:02:18

标签: javascript jquery json

我发现的与此相关的所有问题都是关于组合JSON对象和/或字符串。我正在使用一个名为" Fuse"的jQuery插件来搜索文件的内容(repo here: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文件)。

如果有人能指出我正确的方向,我会非常感激。

2 个答案:

答案 0 :(得分:2)

您的问题归结为,"如何合并数组?"您可以使用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 uphandle 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
});

答案 1 :(得分:0)

感谢Brad,我想出了一个解决方案:

var allData = [];

$.getJSON("data/bn1.json", function(data) {
    allData = allData.concat(data);
    start(allData);
});

$.getJSON("data/bn2.json", function(data2) {
    allData = allData.concat(data2);
    start(allData);
});

万岁!