Andre
Andre

Reputation: 638

Use an object in switch case - javascript

how can I load an object in switch case?

for example, this is my object

{"1":"Restaurant","2":"Hotel","3":"Beauty shop","4":"Physiotherapist","5":"Dentist","6":"Bar","7":"Coffee shop"}

due to multilanguage, I can't write a case for each Business Type, I want to inverse that ID with the BusinessType because is a CSV importer and the client send "Restaurant", if the client send "Restaurant" I have to convert that for "1"

how can I make it become a switch case?

I am looking for it to be inverse

for example

Restaurant = 1

not

1 = Restaurant

this is an example with one case, the object can be different according to the language

  switch (csvItem["Business Type"]){
    case 'Restaurant': csvItem["Business Type"] = 1;
    break;

For nina solution, I have this problem

let businessTypes = document.getElementById('all-business-types').value;

const
  data = businessTypes,
  switched = Object.fromEntries(Object.entries(data).map(([k, v]) => [v, +k]));

console.log('switched ' + switched);

but in my console the result is switched [object Object] and if I use console.log('switched ' + JSON.stringify(switched)); I get this result

{"1":2,"2":19,"3":31,"4":49,"5":71,"6":85,"7":95,"{":0,"\"":110,":":97,"R":6,"e":104,"s":106,"t":81,"a":90,"u":38,"r":91,"n":77,",":93,"H":23,"o":108,"l":27,"B":89,"y":55," ":105,"h":107,"p":109,"P":53,"i":79,"D":75,"C":99,"f":102,"}":111}

businessTypes in my browser log

{"1":"Restaurant","2":"Hotel","3":"Beauty shop","4":"Physiotherapist","5":"Dentist","6":"Bar","7":"Coffee shop"}

thanks for reading :)

Upvotes: 3

Views: 1927

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386680

You could switch the entries and convert the key/string to a number.

const
    json = '{"1":"Restaurant","2":"Hotel","3":"Beauty shop","4":"Physiotherapist","5":"Dentist","6":"Bar","7":"Coffee shop"}',
    data = JSON.parse(json),
    switched = Object.fromEntries(Object
        .entries(data)
        .map(([k, v]) => [v, +k])
    );

console.log(switched);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Usage:

csvItem["Business Type"] = switched[csvItem["Business Type"]];

Upvotes: 2

Ramesh Reddy
Ramesh Reddy

Reputation: 10662

You can try this if you want to invert the keys and values.

const original = {
  "1": "Restaurant",
  "2": "Hotel",
  "3": "Beauty shop",
  "4": "Physiotherapist",
  "5": "Dentist",
  "6": "Bar",
  "7": "Coffee shop"
};


const result = Object.fromEntries(Object.entries(original).map(([k, v]) => [v, k]));

console.log(result)

Upvotes: 1

Related Questions