将小写字符串与未更改的对象键匹配
Matching lowercase string to unaltered object key
我想在不改变原始键的情况下将小写字符串与对象键匹配。稍后我将使用原始形状的钥匙。有办法吗?
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])
}
我想在不改变原始键的情况下将小写字符串与对象键匹配。稍后我将使用原始形状的钥匙。有办法吗?
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])
}