JavaScript Object Properties

In my JavaScript, I am using an object as an associative array. He always has the property of "main", and may have others. So when I create it, I can do this:

var myobject     = new Object ();
myobject["main"] = somevalue;

      

Other properties can be added later. Now, at some point I need to know if myobject has only one property or several, and different actions depend on (I mean only created properties).

So far, all I've found is something like:

flag = false;

for (i in myobject)
     {
     if  (i=="main")  continue;
     flag = true;
     break;
     }

      

and then mark the flag. Or:

for (i in myobject)
     {
     if  (i=="main")  continue;
     do_some_actions ();
     break;
     }

      

These approaches work, but I feel like I forgot something. Is there a better approach?

+2


a source to share


4 answers


I would probably do it like



function hasAsOnlyProperty( obj, prop )
{
  for ( var p in obj )
  {
    if ( obj.hasOwnProperty( p ) && p != prop )
    {
      return false;
    }
  }
  return true;
}

var myobject= new Object();
myobject.main = 'test';

// console requires Firebug
console.log( hasAsOnlyProperty( myobject, 'main' ) ); // true

// set another property to force false    
myobject.other = 'test';

console.log( hasAsOnlyProperty( myobject, 'main' ) ); // false

      

+3


a source


There is an "in" operator:

if ('name' in obj) { /* ... */ }

      



There is also a hasOwnProperty function inherited from the Object prototype that will tell you if an object has a property directly, rather than through prototype inheritance:

if (obj.hasOwnProperty('name')) { /* ... */ }

      

+2


a source


You can use hasOwnProperty to check if an object has this property.

if (myobject.hasOwnProperty("main")) {
    //do something
}

      

+1


a source


If you were able to find out the name of the "next" method assigned to the object you could check as

if (myObject.testMethod) {
    //proceed for case where has > 1 method
}

      

0


a source







All Articles