views:

83

answers:

4

In my JavaScript, I'm using an object as an associative array. It always has the property "main", and may have others. So, when I create it I might do this:

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

Other properties may be added later. Now, at some moment I need to know whether myobject has just the one property, or several, and take different actions depending (I'm only referring to properties I've created).

So far all I've found to do is something like:

flag = false;

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

and then branch on flag. Or:

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

These approaches work but feel to me like I've overlooked something. Is there a better approach?

+1  A: 

You can use hasOwnProperty to check if the object has that property.

if (myobject.hasOwnProperty("main")) {
    //do something
}
juandopazo
+2  A: 

There's an "in" operator:

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

There's also the "hasOwnProperty" function inherited from the Object prototype, which will tell you if the object has the property directly and not via prototype inheritance:

if (obj.hasOwnProperty('name')) { /* ... */ }
Pointy
Well, I at the point in the code in question I need to know whether it has more than one property (i.e. other than "main") that I've assigned. I don't need to know what they are just then.
clothears
Yes, I came to understand that after more carefully reading your question.
Pointy
+1  A: 

If you happened to know the name of the "next" method assigned to the object you could test as

if (myObject.testMethod) {
    //proceed for case where has > 1 method
}
Alex Mcp
+3  A: 

I'd probably do it like this

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
Peter Bailey
Not sure if it's worth making a function for this, I don't need it that often in my code (two or three only). Judging by your reply I guess my general approach is OK.Thanks --
clothears