How to clone Dynamic object in Haxe?
Asked Answered
M

2

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];
}
Mandelbaum answered 21/11, 2017 at 3:47 Comment(0)
C
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.

Continually answered 21/11, 2017 at 7:0 Comment(3)
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?Mandelbaum
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.Continually
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.Mandelbaum
A
2
var newConfig = Reflect.copy(config)
Abundant answered 21/11, 2017 at 7:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.