7.1 Examples: updating an object destructively and non-destructively

The following code shows a function that updates object properties destructively and uses it on an object.

  1. function setPropertyDestructively(obj, key, value) {
  2. obj[key] = value;
  3. return obj;
  4. }
  5. const obj = {city: 'Berlin', country: 'Germany'};
  6. setPropertyDestructively(obj, 'city', 'Munich');
  7. assert.deepEqual(obj, {city: 'Munich', country: 'Germany'});

The following code demonstrates non-destructive updating of an object:

  1. function setPropertyNonDestructively(obj, key, value) {
  2. const updatedObj = {};
  3. for (const [k, v] of Object.entries(obj)) {
  4. updatedObj[k] = (k === key ? value : v);
  5. }
  6. return updatedObj;
  7. }
  8. const obj = {city: 'Berlin', country: 'Germany'};
  9. const updatedObj = setPropertyNonDestructively(obj, 'city', 'Munich');
  10. // We have created an updated object:
  11. assert.deepEqual(updatedObj, {city: 'Munich', country: 'Germany'});
  12. // But we didn’t change the original:
  13. assert.deepEqual(obj, {city: 'Berlin', country: 'Germany'});

Spreading makes setPropertyNonDestructively() more concise:

  1. function setPropertyNonDestructively(obj, key, value) {
  2. return {...obj, [key]: value};
  3. }

Both versions of setPropertyNonDestructively() update shallowly: They only change the top level of an object.