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.
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.
Property accessors provide access to an object's properties by using the dot notation or the bracket notation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With