Reading JS object case insensitive

Let's say we have a Product object with Product.Name, Product.Desc and Product.Price

but for reasons beyond our control we can get a product object with lowercase variables (Product.name, Product.desc, Product.price)

Is there a way to interpret variables that are not case sensitive? Or do I need to do the magic of regular expressions .toLowerCase()

?

Thoughts?

+3


source to share


3 answers


I like Alex Filatov's solution (+1). However, sometimes name variations are known in advance and / or you can only accept certain variations. In this case, it was easier for me to do this:

 Product.Name = Product.Name || Product.name || default.Name;

      



Just OR valid name variations and optionally add a default value.

+3


source


You can add some code to fix the object variable names:

Product.Name = (Product.Name === undefined ? Product.name : Product.Name);

      



However, this must be done for every variable in the object.

+2


source


Compare all 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;
      }
   }
}

      

+2


source







All Articles