Search code examples
javascriptarrayssplice

Splice method used on a copy of an array of objects


I'm a little bit confused about how spread operator works on an array of objects. Let's say I have an array of objects like:

const array = [
{ name: 'Object 1', body: '123'},
{ name: 'Object 2', body: '456'}];

and if I make a clone and use splice on the clone:

const cloneArray = [...array];
const newObject = { name: 'Object 3', body: '789'}
cloneArray.splice(1,1,newObject);

and I will have:

 const array = [
{ name: 'Object 1', body: '123'},
{ name: 'Object 2', body: '456'}];
 const cloneArray = [
{ name: 'Object 1', body: '123'},
{ name: 'Object 3', body: '789'}];

Only the cloned array is modified. The spread operator shouldn't make a shallow copy of the initial array, and force me to deep clone all the objects? What am I missing here?


Solution

  • You're not modifying the array entries.

    splice replaces an array entry. Think of those objects as pointers to a piece of memory:

    const array = [A, B];
    const cloneArray = [...array];
    //    ^ cloneArray = [A, B]
    
    const newObject = C;
    cloneArray.splice(1,1,newObject);
    //    ^ cloneArray = [A, C]
    

    Now, if you were to change the contents of A:

    array[0].foo = 'Bar';
    // Or
    cloneArray[0].foo = 'Bar';
    

    Then you'd see the change in both your source array, as well as in the clone.