Borislav Hadzhiev
Reading timeยท2 min
Photo from Unsplash
Use the spread syntax (...) to add a property to the beginning of an object,
e.g. obj = {one: 1, ...obj};
.
The spread syntax will unpack the key-value pairs of the object after the added property.
let obj = {two: 2, three: 3}; obj = {one: 1, ...obj}; console.log(obj); // ๐๏ธ {one: 1, two: 2, three: 3}
We used the spread syntax (...) to unpack the key-value pairs of an object into a new object.
let obj = {two: 2, three: 3}; const newObj = {...obj}; console.log(newObj); // ๐๏ธ {two: 2, three: 3}
The code sample uses the spread syntax (...) to create a shallow copy of an object.
We need to add a property to the beginning of the object, so we unpack the existing key-value pairs after the property.
let obj = {two: 2, three: 3}; obj = {one: 1, ...obj}; // ๐๏ธ { one: 1, two: 2, three: 3 } console.log(obj);
We added the property at the beginning of the object, so if the property is set in the existing object, it would get overridden.
let obj = {one: 1000, two: 2, three: 3}; obj = {one: 1, ...obj}; // ๐๏ธ { one: 1000, two: 2, three: 3 } console.log(obj);
The one
property already exists on the object, so even though we added the
property to the beginning of the object, the last value of the specified
property wins.
An alternative approach is to use the Object.assign method.
Object.assign()
#Use the Object.assign()
method to add a property to the beginning of an
object, e.g. obj = Object.assign({one: 1}, obj)
.
The Object.assign
method copies the properties from one or more objects to a
target object and returns the result.
let obj = {two: 2, three: 3}; obj = Object.assign({one: 1}, obj); console.log(obj); // ๐๏ธ {one: 1, two: 2, three: 3}
The
Object.assign
method copies all of the properties from a source
object to a target
object.
const obj = Object.assign({a: 1}, {b: 2}, {c: 3}); console.log(obj); // ๐๏ธ { a: 1, b: 2, c: 3 }
The Object.assign()
method takes 2 parameters:
The method returns the target object with the provided properties applied.
The key-value pairs of the second and third objects got copied into the first object.
This enables you to add one or more properties to the beginning of the object.
The ordering would be respected when iterating over the object, just like with the spread syntax.
let obj = {two: 2, three: 3}; obj = Object.assign({one: 1}, obj); for (const key in obj) { console.log(key); // ๐๏ธ one, two, three }
Which approach you pick is a matter of personal preference. I'd use the spread syntax (...) as I find it more readable and intuitive.