The code I have below is currently what I am wanting to see if I can shorten. The code works as-is right now but I don't like the face that each IF statement has its own $each loop in it. I was wanting to see if I can condensed this down
to allow only one call to the $each loop.
switch (input.Type.toLowerCase()) {
case 'slider':
.....[skipped code here]
case 'ddl':
inputContainer.append($("<select>")
.attr("id", input.ID)
.addClass("ctrl")
.addClass("form-item-ddl")
);
if (input.TextField.toLowerCase() == 'gender') {
$.each(input.Data,
function(i, item) {
$("#" + input.ID).append($('<option>', {
value: item.code,
text: item.gender
}));
});
} else if (input.TextField.toLowerCase() == 'race') {
$.each(input.Data,
function(i, item) {
$("#" + input.ID).append($('<option>', {
value: item.code,
text: item.race
}));
});
} else if (input.TextField.toLowerCase() == 'pob') {
$.each(input.Data,
function(i, item) {
$("#" + input.ID).append($('<option>', {
value: item.code,
text: item.pob
}));
});
} else if (input.TextField.toLowerCase() == 'name') {
$.each(input.Data,
function(i, item) {
$("#" + input.ID).append($('<option>', {
value: item.code,
text: item.name
}));
});
} else if (input.TextField.toLowerCase() == 'color') {
$.each(input.Data,
function(i, item) {
$("#" + input.ID).append($('<option>', {
value: item.code,
text: item.color
}));
});
}
break;
case 'checkbox':
...[skipped code here]
Take note that the text: item.****
can be gender, race, pob, name and color. The value: item.code
stays the same for all of them.
So can this be shortened?
1 Answer 1
You can use bracket notation to reference the correct item depending on the content of input.TextField
eg text: item[input.TextField.toLowerCase()]
That way you only need test if input is a valid option. You can use an Array to hold the types and Array.includes to check if the item is in the array.
Thus your code becomes
switch (input.Type.toLowerCase()) {
case 'slider':
.....[skipped code here]
case 'ddl':
inputContainer.append(
$("<select>")
.attr("id", input.ID)
.addClass("ctrl")
.addClass("form-item-ddl")
);
const name = input.TextField.toLowerCase();
const valid = ["gender", "race", "job", "name", "color"].includes(name);
const $e = $("#" + input.ID);
const addItem = (i, it) => {$e.append($('<option>',{value: it.code, text: it[name]}))};
valid && $.each(input.Data, addItem);
break;
case 'checkbox':
...[skipped code here]