3

Lets say we have a Product object with Product.Name, Product.Desc, and Product.Price

but for reasons beyond our control we might recieve 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 have to do some regex .toLowerCase() magic?

Thoughts?

stackoverfloweth
  • 6,669
  • 5
  • 38
  • 69
  • Seems similar to this one: http://stackoverflow.com/questions/21915927/how-to-return-a-result-from-json-with-case-insensitive-search-using-javascript – Donghua Li Jun 07 '15 at 18:25
  • 1
    http://stackoverflow.com/questions/30498314/check-for-matching-key-in-object-regardless-of-capitalization – adeneo Jun 07 '15 at 18:30

3 Answers3

3

I like Alex Filatov's solution (+1). Yet, sometimes the name variations are known in advance and/or you may want to accept only certain variations. In this case I've found it easier to do this:

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

Just OR the acceptable name variations and optionally add a default value.

Yogi
  • 6,241
  • 3
  • 24
  • 30
2

You could add some code to correct the object's variable names:

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

However, this would have to be done for every variable in the object.

AlliterativeAlice
  • 11,841
  • 9
  • 52
  • 69
2

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;
      }
   }
}
Alex Filatov
  • 2,232
  • 3
  • 32
  • 39