How to Deep clone in javascript

前端 未结 19 1558
-上瘾入骨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 03:00

    This works for arrays, objects and primitives. Doubly recursive algorithm that switches between two traversal methods:

    const deepClone = (objOrArray) => {
    
      const copyArray = (arr) => {
        let arrayResult = [];
        arr.forEach(el => {
            arrayResult.push(cloneObjOrArray(el));
        });
        return arrayResult;
      }
    
      const copyObj = (obj) => {
        let objResult = {};
        for (key in obj) {
          if (obj.hasOwnProperty(key)) {
            objResult[key] = cloneObjOrArray(obj[key]);
          }
        }
        return objResult;
      }
    
      const cloneObjOrArray = (el) => {
        if (Array.isArray(el)) {
          return copyArray(el);
        } else if (typeof el === 'object') {
          return copyObj(el);
        } else {
          return el;
        }
      }
    
      return cloneObjOrArray(objOrArray);
    }
    
    0 讨论(0)
提交回复
热议问题