I have some code that adds properties to an object like this:
var MyObject = new Object();
if (....) { MyObject.prop1 = .... ; }
if (....) { MyObject.prop2 = .... ; }
if (....) { MyObject.prop3 = .... ; }
After going through all these if statements, I want to test and see whether MyObject has properties. I don’t want to test if it has prop1 || prop2 || prop3 because there are 12 properties that can be added.
How do I test to see if it has at least one? I tried if (MyObject) but of course that doesn’t work because that only tests the existence of the object. Is these something like a simple one-liner like (MyArray.length) for objects?
If you’re working in a pre-ECMAScript5 environment, it’s easy enough with a small loop:
Or since you’re using
var MyObject = new Object();to create it (BTW, you can just usevar MyObject = {};), you don’t actually need thehasOwnPropertycall:for..inloops through the enumerable properties of an object, both its own and ones it inherits from its prototype;hasOwnPropertytells you whether the property comes from the object itself or its prototype. All of the properties you’re adding will be enumerable, so they’ll show up in the loop. Raw objects ({}) have no enumerable properties initially unless someone has been mucking about withObject.prototype(which is a Really Bad Idea), hence the second loop above.ECMAScript5 (released a couple of years ago, not supported by older browsers and support varies a bit even in more recent ones) adds a couple of functions you could use for this. Probably the most relevant is
Object.keys, which returns an array of the names of the object’s “own” properties (not properties it inherits from its prototype). That would mean you wouldn’t need the loop: