Creating new objects

node v10.24.1
version: 1.2.2
endpointsharetweet
let descriptions; const originalObject = { nestedObject: { description: 'Foo!' }, description: 'Bar!', }; // this doesn't create a new object! const reference = originalObject; reference.description = 'Baz!'; // so now the original description is Baz! and `reference` is just a reference to `originalObject` descriptions = `${originalObject.description} ${reference.description}`;
// let's try destructuring const newObject = { ...originalObject }; newObject.description = 'Qux!'; // so now we have new object that was copied from the original descriptions = `${originalObject.description} ${newObject.description}`;
// what about the nested object? newObject.nestedObject.description = 'Quux!'; // oh, that inner object is just a reference to the nested object within the original object descriptions = `${originalObject.nestedObject.description} ${newObject.nestedObject.description}`;
// let's try again const anotherNewObject = {...originalObject, nestedObject: {...originalObject.nestedObject, description: 'Quuz!' }}; // we created a new object and overwrited the `nestedObject` reference with a new object. descriptions = `${originalObject.nestedObject.description} ${anotherNewObject.nestedObject.description}`;
Loading…

no comments

    sign in to comment