Skip to content

Instantly share code, notes, and snippets.

@argodeep
Last active September 26, 2020 18:21
Show Gist options
  • Save argodeep/d59b40e6ec3d2026606fea3ebc2ffbf0 to your computer and use it in GitHub Desktop.
Save argodeep/d59b40e6ec3d2026606fea3ebc2ffbf0 to your computer and use it in GitHub Desktop.
Object Cloning - Shallow & Deep.
// shallow cloning - object create method
const parent = {
source: function () {
return 'parent';
},
type: 'obj',
hello: {
world: 'Hello World',
state: 'Hello Statesmen',
},
};
const child = Object.create(parent);
child.type = 'new obj';
child.hello.state = 'Hello State';
console.log(parent);
console.log(child.source);
// shallow cloning - object assign method
const parent1 = {
source: function () {
return 'parent1';
},
type: 'obj',
hello: {
world: 'Hello World',
state: 'Hello Statesmen',
},
};
const child1 = Object.assign({}, parent1);
child1.type = 'new obj';
child1.hello.state = 'Hello State';
console.log(parent1);
console.log(child1.source);
// deep cloning - JSON way but not recomended as you can see function/Date etc returns undefined
const parent2 = {
source: function () {
return 'parent2';
},
type: 'obj',
hello: {
world: 'Hello World',
state: 'Hello Statesmen',
},
};
const child2 = JSON.parse(JSON.stringify(parent2));
child2.type = 'new obj';
child2.hello.state = 'Hello State';
console.log(parent2);
console.log(child2.source);
// deep cloning - custom recursive function
const parent3 = {
source: function () {
return 'parent3';
},
type: 'obj',
hello: {
world: 'Hello World',
state: 'Hello Statesmen',
},
};
const child3 = _deepClone(parent3);
child3.type = 'new obj';
child3.hello.state = 'Hello State';
console.log(parent3);
console.log(child3.source);
function _deepClone(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj
}
let newObj = Array.isArray(obj) ? [] : {};
for (const key in obj) {
if (typeof obj[key] === 'object') {
newObj[key] = _deepClone(obj[key]);
} else {
newObj[key] = obj[key];
}
}
return newObj
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment