Last active
March 13, 2019 13:36
-
-
Save munkacsitomi/b0b0edb085a8f6c3a3eb6ed4551ea3ff to your computer and use it in GitHub Desktop.
Different ways to clone objects in Javascript
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
// 1: Deep copy using iteration | |
const iterationCopy = (src) => { | |
let target = {}; | |
for (let prop in src) { | |
if (src.hasOwnProperty(prop)) { | |
target[prop] = src[prop]; | |
} | |
} | |
return target; | |
} | |
const source = {a:1, b:2, c:3}; | |
const target = iterationCopy(source); | |
console.log(target); // {a:1, b:2, c:3} | |
// Check if clones it and not changing it | |
source.a = 'a'; | |
console.log(source.a); // 'a' | |
console.log(target.a); // 1 | |
// 2: Converting to JSON and back | |
const jsonCopy = (src) => JSON.parse(JSON.stringify(src)); | |
const source = {a:1, b:2, c:3}; | |
const target = jsonCopy(source); | |
console.log(target); // {a:1, b:2, c:3} | |
// Check if clones it and not changing it | |
source.a = 'a'; | |
console.log(source.a); // 'a' | |
console.log(target.a); // 1 | |
// 3: Using Object.assign | |
const assignCopy = (src) => Object.assign({}, src); | |
const source = {a:1, b:2, c:3}; | |
const target = assignCopy(source); | |
console.log(target); // {a:1, b:2, c:3} | |
// Check if clones it and not changing it | |
source.a = 'a'; | |
console.log(source.a); // 'a' | |
console.log(target.a); // 1 | |
// This method has a flaw that it only does a shallow copy. | |
// It means that nested properties are still going to be copied by reference. | |
// 4: Deep copy of the object | |
const deepCopy = (src) => { | |
let target = Array.isArray(src) ? [] : {}; | |
for (let key in src) { | |
let k = src[key]; | |
target[key] = k && typeof k === 'object' ? deepCopy(k) : k; | |
} | |
return target; | |
}; | |
const source = {a:1, b:2, c:3}; | |
const target = deepCopy(source); | |
console.log(target); // {a:1, b:2, c:3} | |
// Check if clones it and not changing it | |
source.a = 'a'; | |
console.log(source.a); // 'a' | |
console.log(target.a); // 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment