Last active
September 26, 2020 18:21
-
-
Save argodeep/d59b40e6ec3d2026606fea3ebc2ffbf0 to your computer and use it in GitHub Desktop.
Object Cloning - Shallow & Deep.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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