I want to match a lowercased string to an object key without altering the original key. Later I will use the key in its original shape. Is there a way?
userInput = "SOmekey".toLowerCase(); data = {"SoMeKeY": "Value"}; if (data[userInput]) { for (const [key, value] of Object.entries(data)) { console.log('Unaltered data: ', key, value) } }
Strings are immutable, so if you call .toLowerCase()
on a string, you aren't changing that string, you are creating a new one. So no need to worry about getting back to the original one.
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); } }
Then just lower the case of the object keys to search: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]) }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.