Access JavaScript property case-insensitively?

Try this:

var myObject = { "mIxeDCaSEKeY": "value" };

var searchKey = 'mixedCaseKey';
var asLowercase = searchKey.toLowerCase();
myObject[Object.keys(myObject).find(key => key.toLowerCase() === asLowercase)];

You can alternatively already provide the searchKey in lowercase.

If you want it as a function:

/**
  * @param {Object} object
  * @param {string} key
  * @return {any} value
 */
function getParameterCaseInsensitive(object, key) {
  const asLowercase = key.toLowerCase();
  return object[Object.keys(object)
    .find(k => k.toLowerCase() === asLowercase)
  ];
}

If the key can’t be found, then it’ll return undefined, just like normal.

If you need to support older browsers, then you can use filter instead:

function getParameterCaseInsensitive(object, key) {
  const asLowercase = key.toLowercase();
  return object[Object.keys(object).filter(function(k) {
    return k.toLowerCase() === asLowercase;
  })[0]];
}

I suggest using the polyfills for Object.keys() and Array.filter() if you need even older support.


Note: If you want to also check non-enumerable keys, use Object.getOwnPropertyNames() instead of Object.keys().

Nerdy Note: This assumes your Object doesn’t have a key undefined (eg: const foo = {[undefined]: 'bar'};). That’s just weird.

Leave a Comment