JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to add a property to the beginning of an object in JavaScript?

JavaScript provides two different ways to add a property to the beginning of an object:

  1. Using Object.assign() method.
  2. Using spread operator.

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);
  • Target object can be an empty object or key-value pairs. All the source objects get copied to the target object.
  • Source objects contain properties that you want to merge with the target object.

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
}

Recommended Posts