Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

77
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!