Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access JavaScript property case-insensitively?

Assume I have an object:

var obj = {   foo:"bar",   fizz:"buzz" }; 

I need to access a property of that object dynamically like so:

var objSetter = function(prop,val){   obj[prop] = val; } 

No problems there, except for that prop needs to be case insensitive in case the property name is passed into the function as, say, Foo instead of foo.

So how can I point to an object's property by name without regard to case? I would like to avoid iterating the entire object if possible.

like image 837
Matt Cashatt Avatar asked Sep 18 '12 20:09

Matt Cashatt


People also ask

Are JS object properties case sensitive?

Keys are case sensitive. If you allow someone else to use a key with different case then you are allowing them to create crappy code that is difficult to maintain, not to mention slower since you have to run special code to allow the keys to match when they should not.

What is property access JavaScript?

Property accessors provide access to an object's properties by using the dot notation or the bracket notation.


1 Answers

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 object 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.

like image 57
ShortFuse Avatar answered Sep 29 '22 19:09

ShortFuse