JavaScript provides two different ways to add a property to the beginning of an object:
Object.assign()
method merges two or more objects.
You can use this feature to add a property to the beginning of an object.
let obj = { y: 10, z: 15 } obj = Object.assign({x: 5}, obj); console.log(obj); //{x: 5, y: 10, z: 15}
Object.assign() method accepts two parameters:
Object.assign(targetObject, sourceObject1, sourceObject2, ..., sourceObjectn);
Another approach is to use the spread operator.
ES6 spread operator copies all the properties and values of an object into a new object. The interesting thing is that you can also add a property to the beginning of an object using the spread operator.
let obj = { y: 10, z: 15 } obj = {x: 5, ...obj}; console.log(obj);
Output
{ x: 5, y: 10, z: 15 }