7

I have a Dynamic object from Json and need to clone that in Haxe. Is there any easy way to clone object, please let me know. Or if it's impossible, I want at least iterate that Dynamic object such as JavaScript object.

var config = {
    loop : true,
    autoplay : true,
    path : "data.txt"
};
var newConfig = {};
for (i in config) {
    if (config.hasOwnProperty(i))
        newConfig[i] = config[i];
}
Gama11
  • 31,714
  • 9
  • 78
  • 100
rener172846
  • 431
  • 1
  • 6
  • 19

2 Answers2

10

Use Reflect.copy():

var newConfig = Reflect.copy(config);

Note that it only guaranteed to work on anonymous structures. For other objects, use the appropriate Reflect methods.

Andy Li
  • 5,894
  • 6
  • 37
  • 47
  • Hi Andy, thanks for your answer. By the way what type of values are not guaranteed for that? For example the data parsed from Json will works well? – rener172846 Nov 21 '17 at 07:34
  • 1
    Data parsed from `haxe.Json` can be null, number, string, array, or anonymous objects (same as anonymous structures in Haxe). If you are sure you're parsing an anonymous object, it is safe to use `Reflect.copy()`. Everything else is not guaranteed to work, e.g. null, number, string, array, class instances, enum instances etc. – Andy Li Nov 21 '17 at 09:07
  • Yes, I have tested so the result of Reflect.copy was always anonymous structure though the source object is number, string or array. Thanks for your best solution and perfect experiences. – rener172846 Nov 21 '17 at 16:36
2
var newConfig = Reflect.copy(config)
KevinResoL
  • 982
  • 8
  • 19