Skip to main content
Add a property to an object in JavaScript

Add a property to an object in JavaScript

in this post, We will discuss how to add a property to an object in JavaScript. The objects are key-value pairs. We’ll cover different ways to add a property into the object.

How to Add a Key/Value pair to an Object in JavaScript

There are many ways to add key-value pairs to an Object in JavaScript.

We can add a key/value pair to an Object in JavaScript by the following ways:

  • Using dot (.) notation
  • Use the bracket [ ] notation
  • Using the Object.assign() method
  • Using Spread operator
  • Using third-party library

Using dot notation

A simple approach is to use the dot notation with an assignment operator to add a property to an existing object.

The syntax is:

object.property = value

Simple Example of Dot:

var emp = { name: 'Adam', age: 23 };
emp.salary = 12345;
console.log(emp);

Output:

{ name: 'Adam', age: 23, salary: 12345 }

Using bracket notation

We can add the objects and keys using the bracket notations.

When a property’s name is unknown in advance or if it contains an invalid variable identifier, the dot notation will not function.

The syntax is:

object['property'] = value

Simple Example of Bracket []:

var emp = { name: 'Adam', age: 23 };
emp['salary'] = 12345;
console.log(emp);

Output:

{ name: 'Adam', age: 23, salary: 12345 }

Using Object.assign() Method

The Object.assign() method can copy properties from a source object to a target object. Properties in the sources overwrite the target object’s properties if the same key is found in both objects.

The assign() method allows the user to add multiple key-value pairs within the same code line conveniently.

var emp = { name: 'Adam', age: 23 };
var dept = { dept_name: 'Devops', dept_code: 'IT' };
Object.assign(emp, dept);
console.log(emp);

Output:

{ name: 'Adam', age: 23, dept_name: 'Devops', dept_code: 'IT' }

Using Spread operator

The Spread operator is also used to merge the properties of two objects into a new object. This approach does not overwrite the source object with the properties of the given object for common keys.

var emp = { name: 'Adam', age: 23 };
var dept = { dept_name: 'Devops', dept_code: 'IT' };
var obj = {…emp, …dept};
console.log(obj);

Output:

{ name: 'Adam', age: 23, dept_name: 'Devops', dept_code: 'IT' }

Using Underscore/Lodash Library

There are Underscore and Lodash libraries that offer several utility methods to add properties to an existing object.

You can use any of the .merge, .assignIn (alias .extend), .assign, or _.defaults method.

var _ = require('lodash');
var emp = { name: 'Adam', age: 23 };
var dept = { dept_name: 'Devops', dept_code: 'IT' };
_.merge(emp, dept);
console.log(emp);

Output:

{ name: 'Adam', age: 23, dept_name: 'Devops', dept_code: 'IT' }

Leave a Reply

Your email address will not be published. Required fields are marked *