Add key/value pair to object in JavaScript

How to add key/value pair to object using JavaScript

Posted by Ervin Adams on August 17, 2022

Add key/value pair to object in JavaScript

How to add key/value pair to object using JavaScript

Posted by Ervin Adams on August 17, 2022

Here is how you can add a key/value to an object in JavaScript: 

Option 1. Use dot notation

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

console.log(user);

Option 2. Use bracket notation

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

console.log(user);

Option 3. Use Object.assigned() method

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

console.log(user);