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.
function setPropertyDestructively(obj, key, value) {
obj[key] = value;
return obj;
}
const obj = {city: 'Berlin', country: 'Germany'};
setPropertyDestructively(obj, 'city', 'Munich');
assert.deepEqual(obj, {city: 'Munich', country: 'Germany'});
The following code demonstrates non-destructive updating of an object:
function setPropertyNonDestructively(obj, key, value) {
const updatedObj = {};
for (const [k, v] of Object.entries(obj)) {
updatedObj[k] = (k === key ? value : v);
}
return updatedObj;
}
const obj = {city: 'Berlin', country: 'Germany'};
const updatedObj = setPropertyNonDestructively(obj, 'city', 'Munich');
// We have created an updated object:
assert.deepEqual(updatedObj, {city: 'Munich', country: 'Germany'});
// But we didn’t change the original:
assert.deepEqual(obj, {city: 'Berlin', country: 'Germany'});
Spreading makes setPropertyNonDestructively()
more concise:
function setPropertyNonDestructively(obj, key, value) {
return {...obj, [key]: value};
}
Both versions of setPropertyNonDestructively()
update shallowly: They only change the top level of an object.