Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript object.hasOwnProperty() with a dynamically generated property

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?

like image 884
chris Avatar asked Oct 03 '22 22:10

chris


2 Answers

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

obj = { xxx: false }

typeof obj.xxx // 'boolean'
typeof obj.yyy // 'undefined'
like image 133
punund Avatar answered Oct 12 '22 11:10

punund


I ended up doing a review of my code to figure out overall that I had some mix matched cases. While I was in all doing what I should have, I overwrote one of my variables and caused the object I was looking for to essentially to end up going missing. So in fact false was correct.

So to verify the how or which was proper for me in my case.

obj.hasOwnProperty([theScope+'_enabled']);

was the proper way.

like image 34
chris Avatar answered Oct 12 '22 10:10

chris