Check for matching key in object regardless of capitalization

六眼飞鱼酱① 提交于 2019-12-20 04:49:32

问题


Given a key: 'mykey'

And given an object: Object {Mykey: "some value", ...}

And using the following if (key in myObject) syntax to check for a match...

How can I check matching strings regardless of capital letters?

For example: key mykey should be matched to Mykey in the object even though the M is capitalized.


I am aware of a function to do this: How to uppercase Javascript object keys?

I was looking to see if there was another way.


回答1:


You can create a function that does this, there's no native case-insensitive way to check if a key is in an object

function isKey(key, obj) {
    var keys = Object.keys(obj).map(function(x) {
        return x.toLowerCase();
    });

    return keys.indexOf( key.toLowerCase() ) !== -1;
}

used like

var obj    = {Mykey: "some value"}
var exists = isKey('mykey', obj); // true



回答2:


follow this example

var myKey = 'oNE';
var text = { 'one' : 1, 'two' : 2, 'three' : 3};
for (var key in text){
if(key.toLowerCase()==myKey.toLowerCase()){
//matched keys
    console.log(key)
}else{
//unmatched keys
    console.log(key)
}

}

JavaScript: case-insensitive search



来源:https://stackoverflow.com/questions/30498314/check-for-matching-key-in-object-regardless-of-capitalization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!