How to Deep clone in javascript

前端 未结 19 1466
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:06

How do you deep clone a JavaScript object?

I know there are various functions based on frameworks like JSON.parse(JSON.stringify(o)) and $.extend(t

19条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 02:36

    The Underscore.js contrib library library has a function called snapshot that deep clones an object

    snippet from the source:

    snapshot: function(obj) {
      if(obj == null || typeof(obj) != 'object') {
        return obj;
      }
    
      var temp = new obj.constructor();
    
      for(var key in obj) {
        if (obj.hasOwnProperty(key)) {
          temp[key] = _.snapshot(obj[key]);
        }
      }
    
      return temp;
    }
    

    once the library is linked to your project, invoke the function simply using

    _.snapshot(object);
    

提交回复
热议问题