allencoded
allencoded

Reputation: 7275

Clone Object with arrays using spread operator

How would one go about cloning an object that has arrays in it with the new spread operator?

Example Object:

vehicles: { 
  cars:  [1, 2],
  boats: [3, 4]
}

I want a new object with the arrays in it. In that new object I want to be able to change or add to an array without it referencing and effecting vehicles object.

Upvotes: 2

Views: 1474

Answers (2)

Branchverse
Branchverse

Reputation: 1397

Using JSON.parse(JSON.stringify(object)) to deep copy and object is not the best way if you are looking for performance, rather use a deep copy like this:

let x1 = {
  numbers: {
    number: 1
  }
}
let y1 = copy(x1)
x1.numbers.number++
  console.log(x1)
console.log(y1)

function copy(aObject) { // Deep Clone Object from https://stackoverflow.com/a/34624648/16642626
  if (!aObject) {
    return aObject;
  }

  let v;
  let bObject = Array.isArray(aObject) ? [] : {};
  for (const k in aObject) {
    v = aObject[k];
    bObject[k] = (typeof v === "object") ? copy(v) : v;
  }

  return bObject;
}

Upvotes: 1

D Lowther
D Lowther

Reputation: 1619

Object.assign and the spread operator create shallow clones, only one level deep, beyond that they are referenced. The best way I've found (Thanks MDN) is to use JSON functions to create a true clone.

let vehicles = { 
  cars:  [1, 2],
  boats: [3, 4],
};

let test = JSON.parse(JSON.stringify(vehicles));

console.log(vehicles, test);

test.cars[0] = 5;
vehicles.cars[0] = 7;

console.log(vehicles, test);

Upvotes: 4

Related Questions