1

here:

What is the most efficient way to deep clone an object in JavaScript?

Obviously there are many ways to do it, but I wanted to use the 2nd best answer from this post as it does not use jQuery.

Here is my first try. If this is better for code review please migrate, but it is such a small method.

Pub.cloneDeep = function (obj) {
    _.each(nativeSlice.call(arguments, 1), function (val) {
        _.each(val, function (val_inner, key) {
            obj[key] = JSON.parse(JSON.stringify(val_inner));
        });
    });
    return obj;
};
Community
  • 1
  • 1
  • Are you looking for a clone or for an extend method? – Bergi Jul 01 '14 at 16:54
  • possible duplicate of [Recursive extend in Underscore.js?](http://stackoverflow.com/q/14843815/1048572) – Bergi Jul 01 '14 at 16:55
  • The big drawback of using JSON intermediary is that you lose *all* object types and methods. – Ja͢ck Jul 01 '14 at 17:00
  • Yes, there are many many ways to do it. Please state your exact requirements on what types of objects should be cloned, and what you want to optimize for. – Bergi Jul 01 '14 at 17:00
  • @user3293653 Just look at [this comment](http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object#comment26029072_5344074). – Ja͢ck Jul 01 '14 at 17:23

1 Answers1

1

Per comments, the method needs validation to make sure that the object is composed of types that JSON can handle - they can be found here - www.json.org - on the white box on the side