Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add properties to an object in place, using the spread syntax

The object spread syntax allows for merging an object literal with another object, as in

const additional_object = { c:3, d:4 };
const object = { a:1, b:2, ...additional_object }; // object = { a:1, b:2, c:3, d:4 }

However, I can't find how to use the spread syntax to augment an existing object with new properties, without creating a new object. Rebounding on the previous example, I'd like to write:

const yet_another_object = { e:5, f:6 };
some_syntax_involving_object_here = {...yet_another_object };
// expected result: object = { a:1, b:2, c:3, d:4, e:5, f:6 }

It is easy to create a new object out of 2 objects (const new_objet = { ...object, ...yet_another_object }), but that is not what I need: the const reference to object must hold, and the object must get its additional properties. Note that Object.assign can be used to do so, but I'd assume the spread syntax can do the same in a much more readable way.

like image 351
Jean-Rene Bouvier Avatar asked Sep 13 '25 14:09

Jean-Rene Bouvier


1 Answers

Object.assign(originalObject, newObject) is what you are looking for. It will merge properties of the new object into the existing one, thus saving the reference.

like image 94
ISAE Avatar answered Sep 16 '25 03:09

ISAE