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
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
1 Comment
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
You can use hasOwnProperty to check if the object has that property.
if (myobject.hasOwnProperty("main")) {
//do something
}
Comments
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
}