Based on the Lineman78 answer and taking this other answer from A. Levy into account , I created the following function:
public class JsoUtils {
@SuppressWarnings("unchecked")
public static <T extends JavaScriptObject> T deepCopy(T obj)
{
return (T) deepCopyImpl(obj);
}
private static native JavaScriptObject deepCopyImpl(JavaScriptObject obj) /*-{
if (obj == null) return obj;
var copy;
if (obj instanceof Date) {
// Handle Date
copy = new Date();
copy.setTime(obj.getTime());
} else if (obj instanceof Array) {
// Handle Array
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
if (obj[i] == null || typeof obj[i] != "object") copy[i] = obj[i];
else copy[i] = @com.amindea.noah.client.utils.JsoUtils::deepCopyImpl(Lcom/google/gwt/core/client/JavaScriptObject;)(obj[i]);
}
} else {
// Handle Object
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
if (obj[attr] == null || typeof obj[attr] != "object") copy[attr] = obj[attr];
else copy[attr] = @com.amindea.noah.client.utils.JsoUtils::deepCopyImpl(Lcom/google/gwt/core/client/JavaScriptObject;)(obj[attr]);
}
}
}
return copy;
}-*/;
}
It supports a deep copy of Object, Array, Date, String, Number or Boolean. As explained by A. Levy, the function will work as long as the data in the objects and arrays form a tree structure.
source
share