Is hasOwnProperty method case sensitive JavaScript?

Is the hasOwnProperty() method case sensitive? Is there any other alternative case hasOwnProperty ?

+6
source share
3 answers

Yes, it is case sensitive (so obj.hasOwnProperty('x') !== obj.hasOwnProperty('X') ). You can extend the prototype of the object (some people call this monkey fix ):

 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; }; 
+13
source

Yes, it is case sensitive, because JavaScript is case sensitive.

There is no alternative built into the language, but you can roll:

 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; } 
+3
source

Old question old; but still completely appropriate. I also searched for a quick answer to this question, and eventually figured out what a good solution before I read this, so I decided to share it.

 Object.defineProperty("hasOwnPropertyCI", { "enumerable": false, "value": function(keyName) { return (Object.keys(this).map(function(v){ return v.toUpperCase() }).indexOf(keyName.toUpperCase()) > -1) } }); 

This enables true when keyName exists in the object it calls:

 var MyObject = { "foo": "bar" }; MyObject.hasOwnPropertyCI("foo"); 

Hope this helps someone else !: D

PS: Personally, my implementation throws the conditional expression above into the IF statement, since I will not use it anywhere else in my application (in addition to the fact that I am not a huge fan of manipulating native prototypes).

+1
source

Source: https://habr.com/ru/post/886963/


All Articles