23
Quick ways to clone objects
2021-02-24 - JavaScript
1// JS Tip of the Day
2// Quick ways to clone objects
3
4const hero = { name: 'Batman', weapon: 'Batarang' };
5
6// Spread Operator - Shallow Clone - ES2015/ES6
7const newHeroSpread = { ...hero };
8
9// Rest Operator - Shallow Clone - ES2015/ES6
10const { ...newHeroRest } = hero;
11
12// Object.assign - Shallow Clone - ES2015/ES6
13const newHeroAssign = Object.assign({}, hero);
14
15// JSON methods - Deep Clone (without function or Symbol properties)
16const newHeroJSON = JSON.parse(JSON.stringify(hero));
17
18// Native deep cloning (only Node.js)
19const v8 = require('v8');
20const deepClone = obj => {
21 return v8.deserialize(v8.serialize(obj));
22};
23
24const newHeroV8 = deepClone(hero);
25
26// or Deep Clone with Underscore, Lodash, Ramda, your Custom Function, ...
#JStipoftheday