Matthew Patrick Cashatt Matthew Patrick Cashatt - 5 months ago 22
Javascript Question

Access JavaScript property case-insensitively?

Thanks for looking.

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.

Thanks!

Answer

Compare all the properties of obj with prop.

var objSetter = function(prop,val){
  prop = (prop + "").toLowerCase();
  for(var p in obj){
     if(obj.hasOwnProperty(p) && prop == (p+ "").toLowerCase()){
           obj[p] = val;
           break;
      }
   }
}