Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

113
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda