在开关盒中使用对象 - javascript

Use an object in switch case - javascript

如何在 switch case 中加载对象?

例如,这是我的对象

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

由于多语言,我不能为每个业务类型写一个案例,我想用 BusinessType 反转那个 ID,因为是 CSV 导入器并且客户端发送“Restaurant”,如果客户发送“餐厅”,我必须将其转换为“1”

如何让它成为开关盒?

我正在寻找它是反的

例如

Restaurant = 1

没有

1 = Restaurant

这是一个例子,根据语言不同对象可能不同

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

对于nina的解决方案,我遇到了这个问题

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

但在我的控制台中结果是 switched [object Object] 如果我使用 console.log('switched ' + JSON.stringify(switched)); 我得到这个结果

{"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}

我的浏览器日志中的业务类型

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

感谢阅读:)

您可以切换条目并将 key/string 转换为数字。

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

用法:

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

如果你想反转键和值,你可以试试这个。

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)