Created
June 13, 2019 16:00
-
-
Save Kyngo/95bc4dacf5b59f410638334b1abf7f70 to your computer and use it in GitHub Desktop.
Clone JavaScript objects and Arrays
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
/** | |
* Object and Array cloning system | |
* =============================== | |
* This basically deep clones an object and/or an array depending on its value and type. | |
*/ | |
// clone an array | |
function arrayClone(source) { | |
let target = []; | |
source.forEach((val, idx) => { | |
if (typeof(val) === "object") { | |
if (Array.isArray(val)) { | |
target.push(arrayClone(val)); | |
} else { | |
target.push(objectClone(val)); | |
} | |
} else { | |
target.push(val); | |
} | |
}); | |
return target; | |
} | |
// clone an object | |
function objectClone(source) { | |
let target = {}; | |
Object.keys(source).forEach((idx) => { | |
if (typeof(source[idx]) === "object") { | |
if (Array.isArray(source[idx])) { | |
target[idx] = arrayClone(source[idx]); | |
} else { | |
target[idx] = objectClone(source[idx]); | |
} | |
} else { | |
target[idx] = source[idx]; | |
} | |
}); | |
return target; | |
} | |
/* Proof of Concept */ | |
// a simple object, nothing weird about it | |
const source = [ | |
{ a: 1, b: 2}, | |
{ c: 3, d: { e: [ 4, 5, { x: 1, y: [ 2, 3, 4, [ 5, 6, { z: 4} ] ] } ] } } | |
] | |
// let's clone it... | |
let target = arrayClone(source); | |
// let's tweak a little bit this target | |
target[0].a = 0; | |
target[1].d.e[0] = 0; | |
target[1].d.e[2].x = 0; | |
target[1].d.e[2].y[3][2].z = 0; | |
// and let's see what we get from both! | |
console.log(`source: ${JSON.stringify(source)}`); // source: [{"a":1,"b":2},{"c":3,"d":{"e":[4,5,{"x":1,"y":[2,3,4,[5,6,{"z":4}]]}]}}] | |
console.log(`target: ${JSON.stringify(target)}`); // target: [{"a":0,"b":2},{"c":3,"d":{"e":[0,5,{"x":0,"y":[2,3,4,[5,6,{"z":0}]]}]}}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment