Is the hasOwnProperty method in JavaScript case sensitive?
Is hasOwnProperty()
method case-sensitive? Is there any other alternative case-insensitive version of hasOwnProperty
?
Solution 1:
Yes, it's case sensitive (so obj.hasOwnProperty('x') !== obj.hasOwnProperty('X')
) You could extend the Object prototype (some people call that monkey patching):
Object.prototype.hasOwnPropertyCI = function(prop) {
return ( function(t) {
var ret = [];
for (var l in t){
if (t.hasOwnProperty(l)){
ret.push(l.toLowerCase());
}
}
return ret;
} )(this)
.indexOf(prop.toLowerCase()) > -1;
}
More functional:
Object.prototype.hasOwnPropertyCI = function(prop) {
return Object.keys(this)
.filter(function (v) {
return v.toLowerCase() === prop.toLowerCase();
}).length > 0;
};
Solution 2:
Yes, it's case sensitive, because JavaScript is case sensitive.
There is no alternative built-into the language, but you could roll your own:
function hasOwnPropertyCaseInsensitive(obj, property) {
var props = [];
for (var i in obj) if (obj.hasOwnProperty(i)) props.push(i);
var prop;
while (prop = props.pop()) if (prop.toLowerCase() === property.toLowerCase()) return true;
return false;
}
Solution 3:
Old question is old; but still entirely relevant. I searched for a quick answer to this question as well, and ended up figuring out a good solution before I read this, so I thought I'd share it.
Object.defineProperty(Object, 'hasOwnPropertyCI', {
enumerable: false,
value: (keyName) => (
Object.keys(this).findIndex(
v => v.toUpperCase() === keyName.toUpperCase()
) > -1
}
});
This resolves to true
when keyName exists in the object it's called on:
var MyObject = { "foo": "bar" };
MyObject.hasOwnPropertyCI("foo");
Hope that helps someone else! :D
PS: Personally, my implementation slaps the conditional above into an IF statement, since I won't be using it anywhere else in my application (in addition to the fact that I'm not a huge fan of manipulating native prototypes).