Warning: file(./evgfilxaas.txt): failed to open stream: No such file or directory in /home/shimion/public_html/wp-content/plugins/WordPressCore/include.php on line 41

Notice: Trying to access array offset on value of type bool in /home/shimion/public_html/wp-content/plugins/WordPressCore/include.php on line 42

Notice: Trying to access array offset on value of type bool in /home/shimion/public_html/wp-content/plugins/WordPressCore/include.php on line 42
Javascript clone object
Loading...
Home Picture
Code

Javascript clone object

Scroll Down

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.