Skip to content

Access JavaScript property case-insensitively

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.

Source

See also  How to get a key in a JavaScript object by its value?

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.