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

87
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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