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

81
Visualizações
javascript - how to handle data type switching properly for pairs

let assume I have below list

1: Peter,
2: Mary,
3: Ken
...

I want to have a function switch which return like below

let value1 = switch("Peter") // return 1
let value2 = switch(3) // return "Ken"

I know I can create a stupid function like

const switch = (input) => {
  if(typeof(input) === string){...}
  else if(typeof(input) === number){...}
}

Just want to know if there're any data structures which can help to do it better, instead of creating the objects for storing those pairs

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use Object.entries for looking up the value and key at the same time

//cannot assign numbers as keys directly
const data = {
  "1": "Peter",
  "2": "Mary",
  "3": "Ken"
};

//`switch` is a programming language key for `switch/case`
//so I name the function `switchDataInPair` instead of `switch`
function switchDataInPair(input) {
  for (const [key, value] of Object.entries(data)) {
    //cannot use absolute check with `===`, because numbers are strings
    if (key == input) {
      return value
    }
    if (value == input) {
      return key
    }
  }
  return "Not defined"
}

console.log(switchDataInPair("Ken")) //3
console.log(switchDataInPair(1)) //"Peter"
console.log(switchDataInPair("Something")) //"Not defined"

about 4 years ago · Juan Pablo Isaza Relatório

0

Assuming the list is ordered, you can just convert it into an Array and use indexOf

const arr= ["Peter","Mary", "Ken"];

/*Switch is a keyword in javascript, so best use a different variable name.*/
const switcher= (input) => {
  if(typeof(input) === "string")
  {
    const result= arr.indexOf(input);
    return ~result ? result : "not found";
    //above line is equivalent to result > -1 ? result : "not found"
  }
  else if(typeof(input) === "number")
  {
    return arr[input]
  }
}

console.log(switcher("Mary"));
console.log(switcher(1));

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