1

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?

4 Answers 4

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

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 --
2

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')) { /* ... */ }

2 Comments

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.
Yes, I came to understand that after more carefully reading your question.
1

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

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

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.