Search code examples
javascriptecmascript-6destructuring

Can I use Destructuring to create a deep copy?


Basically I want to get a shallow deep copy that won't change my main object using destructuring.

let a = {
    name: 'lala', 
  testArray: [1,2,3], 
  object: {
    name: 'object', 
    array: [4,5,6]
  }
};

const {name, testArray, object} =  a;

object.array = [...object.array, 0];
console.log(a.object.array);

let b = {
  object2: {
    name: 'object', 
    array: [4,5,6]
  }
};

const object2 =  {...b.object2};
object2.array = [...object2.array, 0];

console.log(b.object2.array);

I made a jsfiddle (for easier reproduction) providing the code I wrote.

https://jsfiddle.net/5z71Lbja/

The problem is that the array of main object also changes when I change the "child" object using the first method(destructuring). The second method works fine but I'm curious if I can achieve the same result using destructuring.


Solution

  • You can't create new objects with destructuring, no. You can only pick out values that exist on the source, you can't perform transformations on them. (You can change the variable name you use, but you can't transform the value.) I've often wanted to, but you can't (at least, not at present).

    There are various jump-through-the-hoops ways you could do it, but really the simplest is going to be to make a shallow copy of the array separately.

    A simpler example:

    const obj = {
      foo: "bar",
      array: [1, 2, 3]
    };
    
    const {foo} = obj;
    const array = obj.array.slice(); // or: = [...obj.array];
    
    obj.array[0] = "one";
    console.log(obj.array[0]); // "one"
    console.log(array[0]);     // 1