Home > Net >  Compress Javascript Options Array
Compress Javascript Options Array

Time:12-09

I've inherited a website and am trying to compress some badly written script. One particular section updates the options in a select field based on other selections. It takes the numeric values from two other select fields in order to update the number of possible options on a third field.

Here is the code in question:

    var value = parseInt(first_value)   parseInt(second_value);
    if(value == 1){
        var newOptions = {"0": "0", "1": "1",};
    } else if(value == 2){
        var newOptions = {"0": "0", "1": "1", "2": "2",};
    } else if(value == 3){
        var newOptions = {"0": "0", "1": "1", "2": "2", "3": "3",};
    } else if(value == 4){
        var newOptions = {"0": "0", "1": "1", "2": "2", "3": "3",  "4": "4",};
    } else if(value == 5){
        var newOptions = {"0": "0", "1": "1", "2": "2", "3": "3",  "4": "4", "5": "5",};
    }

It goes on like this all the way up to value == 30 so it ends up being a lot of code and I am convinced there is a way to reduce it down.

I've tried a few solutions myself which failed entirely, so thought I'd turn to the community to see if anyone has any ideas?

CodePudding user response:

Here's a quick and easy way. By setting the iterator x to -1, we can use x in the while loop. Explicit Number casting ( val) is probably overkill, but handy if the value for val is coming from an input or other HTML element

const getOptions = val => {
  let base = {}, x = -1;
  while (  x <=  val) base[x] = x.toString();
  return base
}

newOptions = getOptions(5);
console.log(newOptions)

CodePudding user response:

Something like this?

   const foo =(value) => {
    let newOptions={0:'0'}
    for (let i = 1; i < value 1; i  ) newOptions[i]=i.toString()   
    return newOptions
   }

   console.log(foo(30))

  • Related