Reputation: 3423
At a certain point in my webapp I have the following (large) series of loops:
jQuery.each(GO, function(index, item){ $("#GO_PUBS").append(
"<li><a href=javascript:dopage('"+item+"');>"+GO_desc[index]+"</a></li>");});
jQuery.each(AP, function(index, item){ $("#AP_PUBS").append(
"<li><a href=javascript:dopage('"+item+"');>"+AP_desc[index]+"</a></li>");});
jQuery.each(BV, function(index, item){ $("#BV_PUBS").append(
"<li><a href=javascript:dopage('"+item+"');>"+BV_desc[index]+"</a></li>");});
jQuery.each(FI, function(index, item){ $("#FI_PUBS").append(
"<li><a href=javascript:dopage('"+item+"');>"+FI_desc[index]+"</a></li>");});
The loop goes on and on but the pattern is always the same.
Is there any way I can make it way shorter by using some sort of array or list instead of explicitly writing it loop?
Thanks
Upvotes: 0
Views: 142
Reputation:
Something like this:
var iterator = function(id, array) {
var $holder = $("#" + id);
return function(index, item) {
$holder.append("<li><a href=javascript:dopage('"+item+"');>"+array[index]+"</a></li>");
};
};
jQuery.each(GO, iterator('GO_PUBS', GO_desc));
jQuery.each(AP, iterator('AP_PUBS', AP_desc));
jQuery.each(BV, iterator('BV_PUBS', BV_desc));
jQuery.each(FI, iterator('FI_PUBS', FI_desc));
If you are able to get hold of all the array(GO, AP,..
) in a map like this:
var collection = {'GO': {asc: GO, desc: GO_desc}, ...};
You will be able to do something like this:
for(var key in collection) {
if(collection.hasOwnProperty(key)) {
var arrMap = collection[key];
jQuery.each(arrMap.asc, iterator(key + '_PUBS', arrMap.desc));
}
}
With 3D array:
var 3dArr = [['GO', GO, GO_desc], ...], 3dArrLen = 3dArr.length, i = 0;
for(i; i < 3dArrLen; i++) {
var v = 3dArr[i];
(function(id, arr, arr_desc) {
jQuery.each(arr, iterator(id + '_PUBS', arr_desc));
})(v[0], v[1], v[2]);
}
Upvotes: 0
Reputation: 3215
function xxx(a, b, c) {
jQuery.each(a, function(index, item){
$(b).append("<li><a href=javascript:dopage('"+item+"');>"+c[index]+"</a></li>");
});
}
xxx(GO, "#GO_PUBS", GO_desc);
xxx(AP, "#AP_PUBS", AP_desc);
xxx(BV, "#BV_PUBS", BV_desc);
xxx(FI, "#FI_PUBS", FI_desc);
Upvotes: 1
Reputation: 14025
DRY (Do not Repeat Yourself) : Start by creating a function to do that :
function createLink(a,b,c){
jQuery.each(a, function(index, item){ $(b).append(
"<li><a href=javascript:dopage('"+item+"');>"+c[index]+"</a></li>");});
}
And call
createLink(BV,"#BV_PUBS",BV_desc);
Upvotes: 1