Add key/value pair to object in JavaScript

How to add key/value pair to object using JavaScript

Posted by Ervin Adams on April 12, 2023

Add key/value pair to object in JavaScript

How to add key/value pair to object using JavaScript

Posted by Ervin Adams on April 12, 2023

In JavaScript, adding a key/value pair to an object is a common operation that can be done in several ways. Here are some of the most common ways to add a key/value pair to an object:

Option 1. Use dot notation

This is the simplest way to add a key/value pair to an object, especially if you know the key name at the time of writing the code. You can use the dot notation to access the object property and assign a value to it. For example:

var user = {
    fname: "Alex",
    lname: "Parker"
};
user.phone = "12345";

console.log(user); //{fname: 'Alex', lname: 'Parker', phone: '12345'}

In this example, we create an object user and then add a key/value pairs using the dot notation. The resulting object will have the properties phone added with the corresponding values.

Option 2. Use bracket notation

This method is useful when you don't know the key name ahead of time or the key name is a variable. You can use the  bracket notation to dynamically add a key/value pair to an object. For example:

var user = {
    fname: "Alex",
    lname: "Parker"
};

const key = "phone";

user[key] = "12345";

console.log(user); //{fname: 'Alex', lname: 'Parker', phone: '12345'}

In the example above, we create a object user and define a variable key with the value "phone". We then use the bracket notation to add a new key/value pair to user with the key name from the variable key and the value "12345".

Option 3. Use Object.assigned() method

This method is used to merge two or more objects into one. It can also be used to add new key/value pairs to an existing object. For example:

var user = {
    fname: "Alex",
    lname: "Parker"
};
Object.assign(user, {phone: "12345"});

console.log(user); //{fname: 'Alex', lname: 'Parker', phone: '12345'}

In this example, we create a object user and use Object.assign() to add a key/value pair to it. The first argument is the target object (user), and the second argument is an object literal with the properties to add.

All three methods are useful for adding key/value pairs to an object in JavaScript. Choose the one that best fits your use case.

This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question