JavaScript object.hasOwnProperty() with a dynamically generated property

chris picture chris · Sep 18, 2013 · Viewed 9.5k times · Source

I have an object that I am passing to a function, that I am trying to figure out if the property exists or not, and when it doesn't, ignore it.

The problem is I keep getting false even when the property is there. For sake of example, I will use an object I posted on another question earlier today...

var myObj = {
       something1_max: 50,
       something1_enabled: false,
       something1_locked: true,
       something2_max: 100,
       something2_enabled: false,
       something2_locked: true,
       something3_max: 10,
       something3_enabled: true,
       something3_locked: true
    }

which gets passed to a function like: buildRetentionPolicyStr('something2', myObj);

So far I’ve got everything I need with this function working perfectly. Until I tried it on live data and realized on the occasion, properties I thought were static and there with defaults otherwise aren't always actually there. So I need to do something I assume with hasOwnProperty() somehow. So in my function I can set a default of my own where if the property exists, use it..

I.e.:

function buildRetentionPolicyStr(theScope, obj)
{
   var myVar = 0;
   if(obj.hasOwnProperty(theScope + '_enabled'))
   {
       myVar = obj[theScope + '_enabled'];
   }
}

In my current test case, the object does in fact exist, so I know that to be true. However, when I do (right above the if statement):

console.log(obj.hasOwnProperty(theScope + '_enabled'));
// Or
console.log(obj.hasOwnProperty([theScope + '_enabled']));

I get this output respective to the order above:

false
// Or
["something2_enabled"]

What is, if there is one, the proper way to check to see if the property exists in this fashion?

Answer

punund picture punund · Sep 18, 2013

A simple way to do that is to run typeof against your property:

obj = { xxx: false }

typeof obj.xxx // 'boolean'
typeof obj.yyy // 'undefined'