To check if an object is empty or not
16,497
Solution 1
If you mean if an Object has no properties:
var isEmpty:Boolean = true;
for (var n in obj) { isEmpty = false; break; }
Solution 2
This is some serious hack but you can use:
Object.prototype.isEmpty = function():Boolean {
for(var i in this)
if(i != "isEmpty")
return false
return true
}
var p = {};
trace(p.isEmpty()); // true
var p2 = {a:1}
trace(p2.isEmpty()); // false
Solution 3
You can also try:
ObjectUtil.getClassInfo(obj).properties.length > 0
The good thing about it is that getClassInfo gives you much more info about the object, eg. you get the names of all the properties in the object, which might come in handy.
Solution 4
If object containes some 'text' but as3 doesn't recognize it as a String, convert it to string and check if it's empty.
var checkObject:String = myObject;
if(checkObject == '')
{
trace('object is empty');
}
Related videos on Youtube
Author by
Ashine
Updated on April 15, 2022Comments
-
Ashine almost 2 years
I want to check in my function if a passed argument of type object is empty or not. Sometimes it is empty but still not null thus I can not rely on null condition. Is there some property like 'length'/'size' for flex objects which I can use here. Please help. Thanks in advance.
-
Ashine over 14 yearsThanks for the help, it was really useful but still can't we have some builtin method like : "myObj.length"/'myObj.isEmpty' Thanks again.
-
Amarghosh over 14 yearsYou are gonna have to extend the
Object
class or theDictionary
class to get an "inbuilt" method for that :) -
JStriedl over 14 yearswow, that's an interesting trick. You just sent me on a quest to learn about the prototype member. Not sure how I might use it, but it's an interesting bit of guts to know about.
-
sharvey over 14 yearsI try to avoid prototypes, because the flex compiler complains alot. And I must admit that I'm an auto-completion addict...
-
sharvey over 14 yearsHis problem is that there's no length field on dynamic objects.
-
AndrewB over 14 yearsThe way I read it is that he did not know if there were a length property or not.
-
AC88 over 14 yearsThere is monkeypatching, but that breaks for .. in loops, which... well... you know.
-
AC88 over 14 yearspossibly check using
this.hasOwnProperty(i)
, in case of other prototype members. -
AC88 about 10 years@Bob:
ObjectUtils
is not a standard API, but yes it would be preferable to patchingObject
. It is actually possible to have a top-level function (putpackage foo { public function bar() { ... } }
in a filefoo/bar.as
), which I stylistically prefer toFooUtils
classes. -
Bob about 10 yearsWhat do you mean by non-standard? help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/…
-
AC88 about 10 years@Bob: Ahh, I was looking for ObjectUtils.
-
Bob about 10 yearsWow sorry, didn't catch that!