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.
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()
Contact Us