All the questions I've found relating to this have been about combining JSON objects and/or strings. I am using a jQuery plugin called "Fuse", for searching the contents of the files (repo here: https://github.com/krisk/Fuse). This is the code I have so far.
$.getJSON("data/bn1.json", function(data) {
start(data);
});
$.getJSON("data/bn2.json", function(data2) {
start(data2);
});
Both JSON files look like this (shortened, for brevity):
[
{
"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!"
}
]
The last JSON file to be called (in this case, bn2.json
) is the one that shows up when I search. I want to search in more than two files (it'll be six files in the future). The full JS file for my project is here: https://github.com/IdeasNeverCease/Gingnet/blob/master/scripts/gingnet.js (you can find my JSON files there too).
If anyone can point me in the right direction, I'd greatly appreciate it.
Your question boils down to, "how do I merge arrays?" You can use Array.concat().
var allData = [];
$.getJSON("data/bn1.json", function(data) {
allData = allData.concat(data);
});
$.getJSON("data/bn2.json", function(data2) {
allData = allData.concat(data);
});
Since you're getting multiple files, it would be best to use promises to wrap these all up and handle them all at once. Untested, but this should get you started:
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With