skip to Main Content

I recently wrote this function for deep cloning an object in javascript, but with the given time complexity it would be extremely slow, any tips on making it more effecient?

function deepClone(obj){
  let clone = {};
  for (let k in obj){
    let v = obj[k];
    if (!array.isArray(v)&&("object"!==typeof v)){
      clone[k]=v;
      continue;
    } else {
      if (typeof v==="object"){
        let RCRSD = deepClone(v);
        clone[k]=RCRSD;
      } else {
        if (array.isArray(v)){
          let arr=[];
          for (let e of v){
            if (typeof e==="object"){
              arr.push(deepClone(e));
            } else {
              arr.push(e)
            };
            clone[k]=arr;
          };
        };
      };
    };
  };
};

This method also does not account for other data structures which is another problem

2

Answers


  1. You can use recursion and check the value of the key

    function deepClone(obj) {
      if (obj === null) {
        return null;
      }
      // create a copy of the object
      let clone = Object.assign({}, obj);
      Object.keys(clone).forEach(
        key =>
        // if the value is another object then do recursion
        (clone[key] =
          typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
      );
      // if the value is an array then just make a new copy of the array
      if (Array.isArray(obj)) {
        clone.length = obj.length;
        return Array.from(clone);
      }
      return clone;
    };
    
    
    const a = {
      foo: 'bar',
      obj: {
        a: 1,
        b: 2
      }
    };
    const b = deepClone(a);
    console.log(a !== b);
    console.log(a.obj !== b.obj)
    Login or Signup to reply.
  2. This isn’t necessarily more efficient (your code seems to be about there sans the weird conditionals), but it does address some bugs in your code (incorrectly handling arrays), and just a bit cleaner.

    function deepClone(obj) {
      if(obj === null) return null
      
      const target = {}
      for(const key in obj) {
        if(typeof obj[key] === "object") {
          if(Array.isArray(obj[key])) {
            target[key] = []
            for(let i = 0; i < obj[key].length; i++) {
              const curr = obj[key][i]
              target[key][i] = typeof curr === "object" ? deepClone(curr) : curr
            }
          } else target[key] = deepClone(obj[key])
        } else
          target[key] = obj[key]
      }
      return Array.isArray(obj) ? Object.values(target) : target
    }
    
    console.log(deepClone({
      hello: "world",
      one: {
        plus: {
          one: 1,
          equals: 2
        }
      },
      fiveWithInflation: 6,
      arr: [1, 2, { hello: [3] }, 4]
    }))
    
    console.log(deepClone([1, 2, 3]))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search