JS Deep Clone

-- 2019-05-16 01:00:

Deep Clone.png


var _deepCloneRecursion = (obj, cloned)=>{
    // deep first approach, loop each prop 
    // until the prop has no key/ not an obj

    var keys = Object.keys(obj);

    keys.forEach(key=>{
        var value = obj[key];

        if(value instanceof Object){
            // save parent node key
            cloned[key] = {};
            // pass the parent node to the next recursion
            this._deepCloneRecursion(value, cloned[key]);
        }else{
            cloned[key] = value;
        }
    })

    return cloned;
}

var objOrigin = {
    "a":{
        "b":"c",
        "d":"e",
        "f":{
            "g":"h"
        }
    },
    "A":{
        "B":"C"
    }
};

var clone = (obj)=>{
    var cloned = {};
    _deepCloneRecursion(obj, cloned);

    return res;
}

var objCloned = clone(objOrigin);

objOrigin.a.f.g = "x";
objCloned.a.f.g = "y";

console.log(objOrigin, objCloned);

-- 2018-07-29
Object.assign 可以实现一层的copy,于是我想用这个方法来迭代复制每一层的,实现deep clone。

目前实现了两层的clone,当object层数超过三层后,不会被复制到新的obj中

Idea,用entries来遍历Object,每个entry保存了obj的key 和 value。
· 当value不是object的时候,就可以去用assign去copy了;
· 否则的话,把key和value(is an object)传入到loop函数里面
· 当存在key时,需要指定key作为节点进行assign,目前是两层,所以只有一个key的情况

· 是否可以通过迭代这个写好的twoLayerClone方法来实现deepClone,因为在key的管理上很棘手。

"use strict";

// Deep clone
/* const a = {a:1,b:{c:1,d:{e:1,f:1}}, c:1}; */
const a = { a: 1, b: { c: {e: 1}, d:3}, c: 1 };

// Two layer clone
const twoLayerClone = function(obj) {
  const resObj = {};
  // [[a,1],[b,{c:1,d:1}]]
    //let keyArr = [];
  
  const _loopObj = (obj, key) => {
    const entries = Object.entries(obj);
    for (let entry of entries) {
      const _obj = {};

      if (typeof entry[1] !== "object") {
        if (!key) {
          _obj[entry[0]] = entry[1];
          Object.assign(resObj, _obj);
        } else {
          if (typeof _obj[key] === "undefined") {
            _obj[key] = {};
          }
          _obj[key][entry[0]] = entry[1];

          if (typeof resObj[key] === "undefined") {
            resObj[key] = {};
          }
          Object.assign(resObj[key], _obj[key]);
          //keyArr.pop();
        }
      } else {
                //keyArr.push(entry[0]);      
        _loopObj(entry[1], entry[0]);
      }
    }
  };
  _loopObj(obj);

  return resObj;
};

const deepClone = function(obj) {
    
};

const aCloned = twoLayerClone(a);
a.a = 2;
a.b.d = 2;

console.log("a", a);
console.log("twoLayerClone", aCloned);

还用Object.keys(), Object.values()尝试得到key之间的关系的规律 ,目前有点mess。
Idea,
· 用allKeys来记录每次迭代时的keys,如果是新的keys,就push进去。当key的value不是object时,需要将allKeys中,这个key删除掉。
· key node表示这个key下面还有object。所有的key node应该在all keys里面出现才对。当key node不在当前allKeys中时,把当前的allKeys pop一层出来,同时pop preKeys,进行迭代查找和更新,找到的时候应该是这个key正确的prekeys了。。

"use strict";
 
// Objet loop
const aObj = {
  a: 1,
  b: 2,
  c: { d: 1, e: { f: 1, g: { n: 1 } } },
  d: { d: 1, e: { f: 1, g: function() {} } }
};
 
let preKeys = [];
 
// key has chance to be a key node
let allKeys = [];
 
const getValues = aObj => {
  let values = Object.values(aObj);
  let keys = Object.keys(aObj);
  if (allKeys.length === 0 || allKeys[allKeys.length - 1] !== keys) {
    allKeys.push(keys);
  }
  console.log("allKeys", allKeys);
  console.log("preKeys",preKeys);
 
  for (let key of keys) {
    if (typeof aObj[key] === "object") {
      console.log("key node", key);
      findKey(key);
      
      getValues(aObj[key]);
      console.log("---");
    } else {
            // Delete the latest track
            allKeys[allKeys.length-1].splice(0,1);
      console.log("keys", keys);
      console.log("currKey", key, "preKeys", preKeys);
      console.log("---");
      /* console.log('value',aObj) */
    }
  }
};
 
const findKey = key => {
  if (!allKeys[allKeys.length - 1].includes(key)) {
    allKeys.pop();
    preKeys.pop();
    findKey(key);
  } else {
    preKeys.push(key);
  }
};
 
getValues(aObj);

你可能感兴趣的:(JS Deep Clone)