Javascript clone object
- JAVASCRIPT
- CODING TIPS
- OBJECT
- CLONE
Published on 2018-08-15
How to do a shallow or deep clone of an Javascript Object using JS ES5, JS ES6 or Lodash. Please note that in the shallow copy the nested properties are just copied by reference.
-
Javascript ES5 JSON.stringify()Deep Clone
Be aware that you can't use JSON.stringify to clone Functions and that Date objects will be stringified in the process.
var clone = JSON.parse(JSON.stringify(obj));Copy code to the clipboard -
Lodash's deep cloneDeep()Deep Clone
var clone = _.cloneDeep(obj, true);Copy code to the clipboard -
Javascript ES6 Object.assign()Shallow CloneFASTEST
const clone = Object.assign({}, obj);Copy code to the clipboard -
Javascript ES6 spread operatorShallow Clone
const clone = {...obj};Copy code to the clipboard -
Lodash's clone()Shallow Clone
var clone = _.clone(obj, true);Copy code to the clipboard
For benchmarking I've used this JSPERF test setup.
Have you enjoyed the read? Please show your support by sharing it with the world 🙌🏻
ShareShareShare