Tech Tip: Merge one object to another with one method
PRODUCT: 4D | VERSION: 17 | PLATFORM: Mac & Win
Published On: March 25, 2019
Copying properties between objects is a common practice while working with objects. Below is a utility method to copy all properties from a source object to target project:
// Name: OB_Assign // Description: Copies values of all properties from source object to target object // Properties of target object will be overwritten by sources with same name. // This method will modify target object // // Parameters: // $1 (Object) - target object // $2 (Object) -source object C_OBJECT($1;$2) ARRAY TEXT($sourcePopertyNames_arr;0) OB GET PROPERTY NAMES($2;$sourcePopertyNames_arr) For ($index;1;Size of array($sourcePopertyNames_arr)) $1[$sourcePopertyNames_arr{$index}]:=$2[$sourcePopertyNames_arr{$index}] End for |
This method is useful when two object need to be merged. Note that this method performs a shallow copy of properties regardless of their type and value. Property values in target object will be overwritten if source object has same property names.
Below is an example:
C_OBJECT($person;$student) $person:=New object() $person.name:="Susan" $person.age:=4 $person.registered:=True $person.family:=New object("Mother";"Kate";"Father";"John";"Brother";"David") $person.profile:=New object("hobby";New object("Dancing";"Very interested")) $student:=New object() $student.name:="Kate" $student.grade:=6 $student.GPA:=New collection(4;3.9;3.5) $student.family:=New object("Mother";"Kate";"Father";"John";"Sister";"Jane") $student.profile:=New object("hobby";New object("Reading";"Every day")) OB_Assign ($person;$student) |
Person object before merging (target):
Student object (source):
Person object after merging: