How do you deep clone a JavaScript object?
I know there are various functions based on frameworks like JSON.parse(JSON.stringify(o)) and $.extend(t
The
JSON.parse(JSON.stringify())combination to deep copy Javascript objects is an ineffective hack, as it was meant for JSON data. It does not support values ofundefinedorfunction () {}, and will simply ignore them (ornullthem) when "stringifying" (marshalling) the Javascript object into JSON.
A better solution is to use a deep copy function. The function below deep copies objects, and does not require a 3rd party library (jQuery, LoDash, etc).
function copy(aObject) {
if (!aObject) {
return aObject;
}
let v;
let bObject = Array.isArray(aObject) ? [] : {};
for (const k in aObject) {
v = aObject[k];
bObject[k] = (typeof v === "object") ? copy(v) : v;
}
return bObject;
}