Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

110
Vistas
Compress Javascript Options Array

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?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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)

about 4 years ago · Juan Pablo Isaza Denunciar

0

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))

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda