How to Deep clone in javascript

前端 未结 19 1837
-上瘾入骨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:57

    The JSON.parse(JSON.stringify()) combination to deep copy Javascript objects is an ineffective hack, as it was meant for JSON data. It does not support values of undefined or function () {}, and will simply ignore them (or null them) when "stringifying" (marshalling) the Javascript object into JSON.

    A better solution is to use a deep copy function. The function below deep copies objects, and does not require a 3rd party library (jQuery, LoDash, etc).

    function copy(aObject) {
      if (!aObject) {
        return aObject;
      }
    
      let v;
      let bObject = Array.isArray(aObject) ? [] : {};
      for (const k in aObject) {
        v = aObject[k];
        bObject[k] = (typeof v === "object") ? copy(v) : v;
      }
    
      return bObject;
    }
    

提交回复
热议问题