Skip to content Skip to sidebar Skip to footer

How To Shorten These Duplicate Javascript Code Into A Loop?

I had ten rows which each rows contain 4 column, now I want to get the value which I had import using localStorage. I find a way to put all these value independently but the code i

Solution 1:

Looking at this repeated line:

document.getElementsByClassName("r1")[0].selectedIndex=res.r1[0];

...a simple first pass improvement would be to just use a nested for loop with variables instead of "r1" and 0:

for (var r = 1; r <= 10; r++) {
  for (var i = 0; i < 4; i++) {
    document.getElementsByClassName("r" + r)[i].selectedIndex = res["r" + r][i];
  }
}

Notice, though, that this means the .getElementsByClassName("r" + r) call happens four time for each value of r, which is not very efficient - it would be better to move that into the outer loop:

var els;
for (var r = 1; r <= 10; r++) {
  els = document.getElementsByClassName("r" + r);
  for (var i = 0; i < 4; i++) {
    els[i].selectedIndex = res["r" + r][i];
  }
}

In the second version the inner loop could say i < els.length rather than i < 4, although note that either way you need to be sure you match the number of HTML elements to the number of items in your res object.

Solution 2:

You've seem to have the jQuery library loaded. Using jQuery makes this much easier.

Here is an example:

var res = JSON.parse(localStorage.getItem("testingvalue"));
$("tr select").each(function(){
   $(this).val(res[$(this).attr("class")][$(this).index()]);
});

Of course, this will only work if the select elements have only one class name and the res object contains values for all the select elements that are inside tr elements. Based on the jQuery code in your question that seems to be the case.

And this is a safer approach

Object.keys(res).forEach(function(key){
    res[key].forEach(function(val, index){
        $("tr select." + key).eq(index).val(val);
    });
});

Solution 3:

Code below will work regardless the size of your data in storage:

res = JSON.parse(localStorage.getItem("testingvalue"));
  // Let's start with checking 'res' type.// - if it's an Array, get the the length from .length// - if it's Object, get the the length from Object.keys().lengthvar resLength = Array.isArray(res) ? res.length : typeof res === 'object' ? Object.keys(res).length : 0;
  // loop throw the rows.for (var i = 0; i < resLength; i++) {
    // Do the same as above: get type of the row and calculate it length for the loop.var rowLength = Array.isArray(res[i]) ? res.length : typeof res[i] === 'object' ? Object.keys(res[i]).length : 0;
    // loop throw the columns on the row.for (var j = 0; j < rowLength; j++) {
      document.getElementsByClassName('r'+i)[j].selectedIndex=res['r'+i][j];
    }
}

Post a Comment for "How To Shorten These Duplicate Javascript Code Into A Loop?"