Tech Tip: Counting Number of Elements in Object
PRODUCT: 4D | VERSION: 17 | PLATFORM: Mac & Win
Published On: December 3, 2019
There are existing commands/member functions that can be used to find the number of items in arrays and collections, but there isn't a built in member function to find the amount of key:value pairs an object contains. Here is a utility method to count the number of paired elements inside an object variable.
This method does not count elements of nested objects/collections within the passed object. Nested objects/collections stored in the passed object will each count as a single element.
The object to be analyzed is passed in through $1 and the number of elements it contains is returned in $0
//----------------------------------------------------- //Method: Object_length //Description: //Counts the number of elements in the object. //Parameters: //$1 - object to be analyzed //$0 - number of elements in the object //----------------------------------------------------- C_OBJECT($1;$ob) C_LONGINT($0) ARRAY TEXT($arr_property;0) ARRAY LONGINT($arr_type;0) If (Count parameters=1) $ob:=$1 OB GET PROPERTY NAMES($ob;$arr_property;$arr_type) $0:=Size of array($arr_property) End if |
Here is an example method that creates an object to be analyzed.
C_OBJECT($ob) $ob:=New object $ob.one:=1 $ob.two:=2 $ob.three:=3 $ob.four:=4 $ob.five:=New object("five";"5";"five_a";"5a") $ob.six:=Null $ob.seven:=New object("seven";"7";"seven_a";"7a") $ob.eight:=Null $ob.nine:=True $ob.ten:="ten" $object_count:=Object_length($ob) |