til / Deep clone objects using structuredClone
A common trick for deep cloning an object in JavaScript is using this JSON-based hack:
JSON.parse(JSON.stringify(object));
It is so common that v8 optimized the performance of just this pattern. However, while it might be fast, it does not work in all cases:
- It removes Functions and
undefined
values - Built-in types like
Map
,Date
, andRegExp
would throw an error - Recursive (cyclic) structures would also cause it to throw an error
You might think that the spread syntax, { ...object }
, could be used to copy an object. But, the spread operator only makes deep copies of data that is not nested. This means that it will only deep copy the top most data, while shallow copying nested data.
const oldObj = { a: { b: 10 }, c: 2 };
const newObj = { ...oldObj };
oldObj.a.b = 2; // This changes b in newObj AND oldObj as the property references the same memory location
oldObj.c = 5; // Only changes c in oldObj
Enter structuredClone
, a new API in JavaScript for deep cloning objects that handles most of these shortcomings.
structuredClone(object);
Note:
structuredClone
does not handle functions and non-cloneables like DOM nodes. In these cases it will throw aDataCloneError
exception.
Even though the API is new, the browser support is good if you are able to target the latest versions.