How to Access JavaScript property case insensitive
var myObject = { "mIxeDCaSEKeY": "value" }; var searchKey = 'mixedCaseKey'; var asLowercase = searchKey.toLowerCase(); myObject[Object.keys(myObject).find(key => key.toLowerCase() === asLowercase)];
Here’s the getter:
Object.defineProperty(Object.prototype, "getProp", { value: function (prop) { var key,self = this; for (key in self) { if (key.toLowerCase() == prop.toLowerCase()) { return self[key]; } } }, //this keeps jquery happy enumerable: false });
Here’s the setter:
Object.defineProperty(Object.prototype, "setProp", { value: function (prop, val) { var key,self = this; var found = false; if (Object.keys(self).length > 0) { for (key in self) { if (key.toLowerCase() == prop.toLowerCase()) { //set existing property found = true; self[key] = val; break; } } } if (!found) { //if the property was not found, create it self[prop] = val; } return val; }, //this keeps jquery happy enumerable: false });
Now that we’ve created those functions, our code is super clean and concise and just works.
Case-insensitive getting:
var obj = {foo: 'bar', camelCase: 'humpy'} obj.getProp("FOO"); //returns 'bar' obj.getProp("fOO"); //returns 'bar' obj.getProp("CAMELCASE"); //returns 'humpy' obj.getProp("CamelCase"); //returns 'humpy'
Case-insensitive setting:
var obj = {foo: 'bar', camelCase: 'humpy'} obj.setProp('CAmelCasE', 'super humpy'); //sets prop 'camelCase' to 'super humpy' obj.setProp('newProp', 'newval'); //creates prop 'newProp' and sets val to 'newval' obj.setProp('NewProp', 'anotherval'); //sets prop 'newProp' to 'anotherval'