How to use the script once, and paste it every time?

I have a script:

$.getJSON('/js/db04.json', function (data) {
 $(data).each(function(index, item) {
$('#table').append(
 '<tr><td class="col1">'+ item.title01 +'</td><td class="col2">' + item.shopcode + '</td><td> <a href="' + item.link + '">' + item.title + '</a></td><td class="col3">' + item.cost + '</td></tr>'
);
});
});

It pulls data from a JSON file, such files have a lot of, how to modify so that the code is not inserted for each file with data, and use it once.
April 4th 20 at 13:28
2 answers
April 4th 20 at 13:30
Solution
Move it into a separate function and pass the desired parameters, which may change from call to call as arguments.

getJsonAndUpdateTable function(jsonPath) {
 $.getJSON(jsonPath, function (data) {
 $(data).each(function(index, item) {
$('#table').append(
 '<tr><td class="col1">'+ item.title01 +'</td><td class="col2">' + item.shopcode + '</td><td> <a href="' + item.link + '">' + item.title + '</a></td><td class="col3">' + item.cost + '</td></tr>'
);
});
});
}

And then call this function where necessary and pass inside the path to your json file.
Thank You Very Much!!! - elmore33 commented on April 4th 20 at 13:33
April 4th 20 at 13:32
Solution
For reusing code functions are used.

function doMagic(path) {
$.getJSON(path, function (data) {
 $(data).each(function(index, item) {
$('#table').append(
 '<tr><td class="col1">'+ item.title01 +'</td><td class="col2">' + item.shopcode + '</td><td> <a href="' + item.link + '">' + item.title + '</a></td><td class="col3">' + item.cost + '</td></tr>'
);
});
});
}

doMagic('/js/db04.json')
doMagic('/js/db05.json')

// or
['/js/db04.json', '/js/db05.json', '/js/db06.json'].forEach(doMagic)
Thank You Very Much!!! - elmore33 commented on April 4th 20 at 13:35

Find more questions by tags JavaScriptJSON