【问题标题】:Matching lowercase string to unaltered object key将小写字符串与未更改的对象键匹配
【发布时间】:2021-02-15 18:10:29
【问题描述】:

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

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

【问题讨论】:

    标签: javascript object matching lowercase


    【解决方案1】:

    字符串是不可变的,所以如果你在一个字符串上调用.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);
      }
    }

    【讨论】:

    • 谢谢。不过,这确实需要 cpu 进行一些迭代,对吧?
    • @DIProgan 不确定您的意思。任何循环都会导致迭代。所有操作最终都由 CPU 进行。
    【解决方案2】:

    然后只需降低要搜索的对象键的大小写: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])
    }

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多