piątek, 1 lipca 2016

shallow and deep cloning objects in JavaScript

As all values in JavaScript are pass by reference clonig is quite popular operation, to save original object. Unfortunately JavaScript does not provide any method to clone deeply the whole object.

ES6 provided some features, which could be useful, but still we have to remember, that this is only a shallow cloning.

The first solution is to use Object.assign:
const a = {
  b: {
    c: 1
  },
  z: 15
};

console.log(a); // {"b":{"c":1},"z":15}

let d = Object.assign({}, a);

d.b.c = 5;
d.z = 29;

console.log(a); // {"b":{"c":5},"z":15}
console.log(d); // {"b":{"c":5},"z":29}

The first console.log will display original a object, but in the second a.b.c value will be changed. Only a.z value will stay the same. This is what shallow cloning is. Only first level properties are cloned, rest is passed by reference.

So what would happen if d.b would be changed?
d.b = 118;

console.log(a); // {"b":{"c":5},"z":15}
console.log(d); // {"b":118,"z":29}

The same situation will happen if we will use spread operator:
const aa = {
  g: {
    h: 1
  },
  y: 15
};

console.log(aa); // {"g":{"h":1},"y":15}

let e = { ...aa };

e.g.h = 9;
e.y = 23;
console.log(aa); // {"g":{"h":9},"y":15}

So, how to make a deep cloning in JavaScript?

1. Use JSON stringify and parse
JSON.parse(JSON.stringify(object));

2. Write own method to do a deep clone of passed object.

Brak komentarzy:

Prześlij komentarz