Thought leadership from the most innovative tech companies, all in one place.

How to add a key to an object in JavaScript

Introduction

In JavaScript, objects are a powerful data structure that allows you to store and manipulate complex data. One of the most common tasks when working with objects is adding new properties to them.

In this blog post, we'll explore how to add keys to an object in JavaScript, and provide you with an example of how to use this functionality in your code.

Dot Notation

To add a new key to an object in JavaScript, we can simply use the dot notation or square bracket notation to specify the key and assign a value to it. Let's say we have an object that represents a person, and we want to add their age to it. Here's an example using dot notation:

const person = {
  name: "John Doe",
  email: "john.doe@example.com",
};

person.age = 30;

console.log(person); // Outputs { name: "John Doe", email: "john.doe@example.com", age: 30 }

In this code, we add a new key age to the person object and assign a value of 30 to it using the dot notation.

Square Bracket Notation

Alternatively, we can use the square bracket notation to add a new key to an object. This notation is useful when we want to use a variable or a string that contains a special character as the key. Here's an example using square bracket notation:

const person = {
  name: "John Doe",
  email: "john.doe@example.com",
};

const key = "age";

person[key] = 30;

console.log(person); // Outputs { name: "John Doe", email: "john.doe@example.com", age: 30 }

In this code, we first create a variable key that contains the string "age". We then use the square bracket notation to add a new key to the person object and assign a value of 30 to it.

Nested objects

In addition, if the object is a nested object, we can use the dot or square bracket notation to add a new key to the nested object as well. Here's an example:

const person = {
  name: "John Doe",
  contact: {
    email: "john.doe@example.com",
    phone: "123-456-7890",
  },
};

person.contact.address = "123 Main St.";

console.log(person); // Outputs { name: "John Doe", contact: { email: "john.doe@example.com", phone: "123-456-7890", address: "123 Main St." }}

In this code, we use the dot notation to access the contact property of the person object, and then add a new key address to the nested object using dot notation.

Conclusion

In conclusion, adding keys to an object in JavaScript is a simple and straightforward task that can be accomplished using either dot notation or square bracket notation. By using these methods, we can easily add new properties to an object and manipulate data in our applications as needed.

If you're interested in learning more about the objects and object methods in JavaScript, visit MDN's page on Objects.




Continue Learning