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

To add a key/value pair to a JavaScript object, you can use several methods depending on your use case. Below are the most common approaches with examples and explanations:

1. Dot Notation (Static Key)

Use when the key is a valid identifier (no spaces/special characters) and known upfront:

const obj = { name: "Alice" };
obj.age = 30; // Add key "age" with value 30

// Result: { name: "Alice", age: 30 }

2. Bracket Notation (Dynamic Key)

Use when the key is dynamic, contains special characters, or is stored in a variable:

const obj = { "full name": "Bob Smith" };
const key = "country";

// Add dynamic key
obj["isAdmin"] = true; // Key with special naming
obj[key] = "Canada";   // Key from variable

// Result: { "full name": "Bob Smith", isAdmin: true, country: "Canada" }

3. Object Spread Operator (Immutable Update)

Create a new object without modifying the original (common in React/Redux for state immutability):

const original = { a: 1, b: 2 };
const updated = { ...original, c: 3 }; // Add key "c"

// Result: { a: 1, b: 2, c: 3 }

4. Object.assign() (Merge Objects)

Merge properties into an existing or empty object:

const obj = { id: 100 };
Object.assign(obj, { role: "user" }); // Mutates original object

// Result: { id: 100, role: "user" }

// Immutable alternative:
const newObj = Object.assign({}, obj, { role: "user" });

5. Computed Property Names (ES6)

Dynamically define a key when creating an object literal:

const key = "status";
const obj = {
  [key]: "active", // Key is dynamically set to "status"
  score: 95
};

// Result: { status: "active", score: 95 }

Key Scenarios & Edge Cases

ScenarioSolution
Add multiple keysUse Object.assign() or spread operator: { ...obj, key1: 1, key2: 2 }
Nested objectsUpdate nested properties directly: obj.details = { email: "test@example.com" }
Overwrite existing keysReassign the value: obj.age = 31
Symbols as keysUse bracket notation with a Symbol: obj[Symbol("id")] = 123

Performance Considerations

  • Dot/Bracket Notation: Fastest for direct mutations.
  • Spread/Object.assign(): Slightly slower (creates new objects) but safer for immutability.

Example Workflow

// Initialize object
const user = { name: "Charlie" };

// Add static key
user.age = 28;

// Add dynamic key
const roleKey = "userRole";
user[roleKey] = "admin";

// Add nested property
user.address = { city: "Paris" };

// Immutable update
const updatedUser = { ...user, isVerified: true };

// Final result:
// {
//   name: "Charlie",
//   age: 28,
//   userRole: "admin",
//   address: { city: "Paris" },
//   isVerified: true
// }

Choose the method that aligns with your needs for mutability, key type, and code style!

Leave a Reply

Your email address will not be published. Required fields are marked *