将小写字符串与未更改的对象键匹配

问题描述

我想在不改变原始键的情况下将小写字符串与对象键匹配。稍后我将使用原始形状的钥匙。有办法吗?

userInput = "SOmekey".toLowerCase();
data = {"SoMeKeY": "Value"};
if (data[userInput]) {
    for (const [key,value] of Object.entries(data)) {
        console.log('Unaltered data: ',key,value)
    }
}

解决方法

字符串是不可变的,所以如果你对一个字符串调用 .toLowerCase(),你不是在改变那个字符串,而是在创建一个新的字符串。所以不用担心会变回原来的。

userInput = "SOmekey";
data = {"SoMeKeY": "Value"};

for (key in data){
  // Neither key or userInput are changed by creating
  // lower cased versions of them. New strings are created
  // and those new strings are used here for comparison.
  if(key.toLowerCase() === userInput.toLowerCase()){
    console.log(key,data[key],"| Original user input: ",userInput);
  }
}

,

然后只需降低要搜索的对象键的大小写:D

userInput = "SOmekey".toLowerCase();
data = {"SoMeKeY": "Value"};

//object's keys except they are lowered as well
let loweredKeys=Object.keys(data).map(a=>a.toLowerCase())

//now for verification
if(loweredKeys.includes(userInput)){
  let keyIndex=loweredKeys.indexOf(userInput)
  let values=Object.values(data)
  let keys=Object.keys(data)
  console.log("Unaltered data: ",keys[keyIndex],values[keyIndex])
}