Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the hasOwnProperty method in JavaScript case sensitive?

Tags:

javascript

Is hasOwnProperty() method case-sensitive? Is there any other alternative case-insensitive version of hasOwnProperty?

like image 329
Arjun Avatar asked Apr 29 '11 13:04

Arjun


People also ask

What does hasOwnProperty do in JavaScript?

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

Are JavaScript objects case sensitive?

Is Javascript Case Sensitive? JavaScript is a case-sensitive language. This implies that the language keywords, variables, operate names, and the other identifiers should be typewritten with an identical capitalization of letters.

Is JavaScript case insensitive or case sensitive?

JavaScript is Case Sensitive All JavaScript identifiers are case sensitive.

What's the difference between the in operator and the hasOwnProperty method in objects?

So what's the difference between the two? The key difference is that in will return true for inherited properties, whereas hasOwnProperty() will return false for inherited properties.


1 Answers

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;
};
like image 172
KooiInc Avatar answered Sep 18 '22 14:09

KooiInc