Borislav Hadzhiev
Last updated: Nov 11, 2021
Check out my new book
Use the spread operator (...) to add a property to the beginning of an object,
e.g. obj = {one: 1, ...obj};
. The spread operator unpacks the key-value pairs
of an object into a new object, allowing us to add one or more properties to the
beginning.
// ✅ Using spread syntax (...) let obj1 = {two: 2, three: 3}; obj1 = {one: 1, ...obj1}; console.log(obj1); // 👉️ {one: 1, two: 2, three: 3}
We used the spread operator (...) to unpack the key-value pairs of an object into a new object.
let obj1 = {two: 2, three: 3}; // 👇️ creates a shallow copy of `obj1` const newObj = {...obj1}; console.log(newObj); // {two: 2, three: 3}
Because we prepended the property one
to the beginning and unpacked the rest
at the end, the order is preserved and would be respected when iterating over
the object, e.g. in a for...in
loop.
let obj1 = {two: 2, three: 3}; obj1 = {one: 1, ...obj1}; // 👇️ order is respected for (const key in obj1) { console.log(key); // one, two, three }
An alternative approach is to use the Object.assign method.
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.
// ✅️ Using Object.assign let obj2 = {two: 2, three: 3}; obj2 = Object.assign({one: 1}, obj2); console.log(obj2); // 👉️ {one: 1, two: 2, three: 3}
We passed the following parameters to the Object.assign
method:
// 👇️ {a: 1, b: 2, c: 3} console.log(Object.assign({a: 1}, {b: 2}, {c: 3}));
The key-value pairs from the second and third objects got copied into the first object, which allows us 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 operator:
let obj2 = {two: 2, three: 3}; obj2 = Object.assign({one: 1}, obj2); for (const key in obj2) { console.log(key); // 👉️ one, two, three }
Some browsers may iterate over an object in an arbitrary order, so it's not
100%
guaranteed that the insertion order will be respected.
If you need to be certain that the insertion order of key-value pairs in an object is respected, you should use a Map instead.
Map
stores key-value pairs and remembers the insertion order of the keys.