stackoverfloweth
stackoverfloweth

Reputation: 6917

Read JS object without case sensitivity

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?

Upvotes: 3

Views: 100

Answers (3)

Yogi
Yogi

Reputation: 7229

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.

Upvotes: 3

Alex Filatov
Alex Filatov

Reputation: 2321

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

Upvotes: 2

AlliterativeAlice
AlliterativeAlice

Reputation: 12577

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.

Upvotes: 2

Related Questions