如何解决将小写字符串与未更改的对象键匹配
我想在不改变原始键的情况下将小写字符串与对象键匹配。稍后我将使用原始形状的钥匙。有办法吗?
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])
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。