Would you like to clone this notebook?

When you clone a notebook you are able to make changes without affecting the original notebook.

Cancel

JS Objects Clone

node v8.17.0
version: 1.0.0
endpointsharetweet
http://www.daleseo.com/js-objects-clone/
const original = { num: 1000, bool: true, str: 'test', func: function () { console.log('func') }, obj: { x: 1, y: 2 }, arr: ['A', 'B', 'C'] }
/* Reference Assignment */ const clone1 = original original.num = 2000 console.log(clone1.num) // 2000 clone1.bool = false console.log(original.bool) // false console.log(original === clone1) // true
/* Shallow Clone: Object.assign(obj) */ const clone2 = Object.assign({}, original) original.num = 3000 console.log(clone2.num) // 2000 clone2.bool = true console.log(original.bool) // false console.log(original === clone2) // false
original.obj.x = 3 console.log(clone2.obj.x) // 3 clone2.arr.push('D') console.log(original.arr) // ["A", "B", "C", "D"] console.log(original.obj === clone2.obj) // true console.log(original.arr === clone2.arr) // true
/* Shallow Clone: Spread Operator */ const clone3 = {...original} original.num = 4000 console.log(clone3.num) // 3000 clone3.arr.push('E') console.log(original.arr) // ["A", "B", "C", "D", "E"] console.log(clone3.arr === original.arr) // true
/* Deep Clone: JSON.parse(JSON.stringify(obj)) */ const clone4 = JSON.parse(JSON.stringify(original)) original.obj.x = 4 console.log(clone4.obj.x) // 3 clone4.arr.push('F') console.log(original.arr) // ["A", "B", "C", "D", "E"] console.log(original.obj === clone4.obj) // false console.log(original.arr === clone4.arr) // false
console.log(original.func) // function func() console.log(clone4.func) // undefined
/* Deep Clone: On my own */ function clone(source) { var target = {}; for (let i in source) { if(source[i] != null && typeof(source[i]) === "object") { target[i] = clone(source[i]) // resursion } else { target[i] = source[i] } } return target; } const clone5 = clone(original) console.log(original.func) // function func() console.log(clone5.func) // function func()
const _ = require('lodash') const clone6 = _.cloneDeep(original) console.log(original.func) // function func() console.log(clone6.func) // function func()
Loading…

no comments

    sign in to comment