How to use Objcet.assign() method In Javascript

In this approach, we are using Objcet.assign() method to assign the key and value to the object. We are passing the object name and the field that we want to use in the object. It assign those fields to the given object.

Example: This example shows the implementation of the above approach.

Javascript
const obj = { Organisation: "GFG" };
Object.assign(obj, { field: "CS" });
console.log(obj); 

Output
{ Organisation: 'GFG', field: 'CS' }

How to add key/value pair to a JavaScript object ?

JavaScript object has key-value pair and it can be of variable length. We first need to declare an object and assign the values to that object for that there can be many methods. In this article, we are going to apply different approaches to adding a key/value pair to a JavaScript object.

These are the following methods to add a key/value pair to a JavaScript object:

Table of Content

  • Using Dot Notation
  • Using Bracket Notation
  • Using Spread operator
  • Using Objcet.assign() method
  • Using Objcet.defineProperty() method
  • Using Object.entries() and Object.fromEntries()


Similar Reads

Using Dot Notation

In this approach, we will directly access the key of an object by “.” for assigning the value to it. It can be a repeated method as every time we need to define a different key for different values....

Using Bracket Notation

In this approach, we are using Bracket to access the key and assign the value to it....

Using Spread operator

In this approach, we are using Spread operator to assign the value to the object. we will create a new object and by using the spread operator we can add the old key and value to the new object with new key value pair....

Using Objcet.assign() method

In this approach, we are using Objcet.assign() method to assign the key and value to the object. We are passing the object name and the field that we want to use in the object. It assign those fields to the given object....

Using Objcet.defineProperty() method

In this approach, we are using Objcet.defineProperty() method to assign the key and value to the object. We are passing the object name and the field that we want to use in the object with some extra specification that is served by the method itself....

Using Object.entries() and Object.fromEntries()

In this approach, we are using Object.entries() to convert the object into an array of key-value pairs, then adding the new key-value pair, and converting it back to an object using Object.fromEntries()....

Contact Us