Created
October 13, 2014 13:35
-
-
Save grapefrukt/a595b8c1fd2a83b76e45 to your computer and use it in GitHub Desktop.
Recursively applies the values from one object to another using reflection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static function setconfig(target:Dynamic, config:Dynamic) { | |
// iterate over the fields of the config object | |
for (key in Reflect.fields(config)) { | |
// make sure our target has this field | |
if (!Reflect.hasField(target, key)) continue; | |
// fetch the value of the first field | |
var configvalue:Dynamic = Reflect.field(config, key); | |
// check if its and object, and if so, make sure it actually has multiple values inside | |
// (strings are for some reason considered objects) | |
if (Reflect.isObject(configvalue) && Reflect.fields(configvalue).length > 0) { | |
// if the target also has a field named like this, recurse into it | |
if (Reflect.hasField(target, key)) { | |
setconfig(Reflect.field(target, key), Reflect.field(config, key)); | |
} else { | |
trace('target ($target) has no $key'); | |
} | |
// if it's not an object, it's a plain value and we can set it | |
} else { | |
Reflect.setProperty(target, key, configvalue); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment