Skip to content Skip to sidebar Skip to footer

Javascript Object Check For Key -- But Ignore Case

Normally, I would do it like this if (key in obj) { //other stuff } But I don't actually know that they are capitalized the same. What's the best way to do this? I would rathe

Solution 1:

Long Code But Faster

var key, keys = Object.keys(obj);
var n = keys.length;
var objArr=[]
while (n--) {
  objArr.push(keys[n].toLowerCase());
}

if (objArr.indexOf(key)!==-1) {
        //other stuff on obj
}

Short Code, Less Efficient

var objTemp = JSON.parse(JSON.stringify(obj).toLowerCase());

Now check in

if (key in objTemp) {
    //other stuff on obj
}

Solution 2:

Presumably you don't know what the key-casing is because you're getting the objects from a 3rd party source, such as an AJAX call or other script resource load. You can interject a normalization method at that point and only have to loop once per object, making it a static overhead cost.

For example, define a method

functionnormalizeObjectKeys(obj) {
  for (key in obj) {
    obj[key.toUpperCase()] = foo[key];
    delete obj[key];
  }
}

Calling it like this in my Chrome javascript console seems to prove it works.

> var foo = { bar: "bar", baZ: "baZ" }
undefined
> foo
Object {bar: "bar", baZ: "baZ"}
> normalizeObjectKeys(foo)
undefined
> foo
Object {BAR: "bar", BAZ: "baZ"}

Then you always check for the uppercase version of the key. It's not pretty, and will collide if there are different cases of the same key (e.g. foo = {bar : "bar", Bar : "baz" } could wind up with either value of BAR), but it might suit your purposes. If you really need to know, you could check whether obj[key.toUpperCase] == undefined before setting the value and log an error or throw an exception.

Solution 3:

Here's what you want:

functionlowerCaseObjectKeys(object) {
  // clone the original object so that we don't modify its stateconst newObject = Object.assign({}, object);

  Object.keys(newObject).forEach((key) => {
    // if key is already lower-case, skip it & move on!if (key.toLowerCase() === key) {
      return;
    }

    // set a new, lower-cased key in newObject
    newObject[key.toLowerCase()] = newObject[key];
    // delete the original, non-lower-cased key (& value) from newObjectdelete newObject[key];
  });

  return newObject;
}

Now, you can fetch a value from an object, regardless of the casing of the key:

lowerCaseObjectKeys( yourObjectHere )[ 'lowercasedkeyhere' ];

Post a Comment for "Javascript Object Check For Key -- But Ignore Case"