Javascript clone object

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));

  • Lodash’s deep cloneDeep()Deep Clone

    var clone = _.cloneDeep(obj, true);

  • Javascript ES6 Object.assign()Shallow CloneFASTEST

    const clone = Object.assign({}, obj);

  • Javascript ES6 spread operatorShallow Clone

    const clone = {...obj};

  • Lodash’s clone()Shallow Clone

    var clone = _.clone(obj, true);

For benchmarking I’ve used this JSPERF test setup.