Deep Copy methods
JSON.parse(JSON.stringify())
Service Workers postMessage() onmessage
History API history.pushState(obj, title) history.state
Notification API new Notification("title", {data: obj} ).data
Build a custom recursive function
Deep Cloning Objects - The modern way
//only contains primitive types
const shallowArray = ["false", 123, "pedbad", null, undefined];
//contains both primitive and object types
const deepArray = [
false,
123,
"pedbad",
["Alpha", "Beta", "Delta"],
{ firstName: "John", lastName: "Doe" }
];
const deepObj = {
coins: ["xrp", "bitcoin", "xlm", "kava"],
exchanges: ["Binance", "Coinbase", "Bitrue"],
altSeason: false,
fomo: 5
};
const newObj = { ...deepObj };
newObj.exchanges[0] = 'UniSwap'; //changed inside ref.
newObj.coins = ['etheriunm', 'dent']; //new ref
console.log(newObj, deepObj);
let otherObj = JSON.parse(JSON.stringify(deepObj));
otherObj.exchanges[0] = 'UniSwap';
console.log(otherObj, deepObj);
Shallow Copy Method examples
arr1.slice(0)
[].concat(arr1)
Object.create({}, obj)
Object.assign({}, obj)
Array.from(arr1)
let s = "steve";
let g = s;
s = "new value";
console.log(s, g);
let arr = Array.from(shallowArr);
//let arr1 = [...shallowArr];
shallowArr[0] = 456;
//console.log(arr, shallowArr);
Deep Cloning Objects - The modern way
There's now a native way in JavaScript to do deep copies of objects.
The structuredClone
function is now built into the JavaScript runtime:
const myDeepCopy = structuredClone(myOriginal);
Great article here:
Deep-copying in JavaScript using structuredClone