Course contentsShow
← JavaScript
Lesson 617 of 2,72315. ObjectsFree lesson

Combining Computed Keys and Values

Create objects where both the key and value are expressions evaluated dynamically.

Combining Computed Keys and Values

What you'll learn: How to use expressions for both the property name and its value when creating objects.

You've already seen computed property names using bracket notation ([expression]) and shorthand values. Now let's combine these techniques: using expressions to dynamically calculate both what the property should be called and what value it should hold.

The Core Idea

When building objects, you can wrap any expression in square brackets for the key, and use any expression for the value. JavaScript evaluates both before adding them to the object:

const prefix = "user";
const id = 42;
const status = "active";

const user = {
  [prefix + "Id"]: id * 10,  // Key AND value are computed
  [prefix + "Status"]: status.toUpperCase()
};

console.log(user);  // { userId: 420, userStatus: "ACTIVE" }

Both prefix + "Id" (key) and id * 10 (value) are evaluated dynamically. This is powerful when generating objects from data or configuration.

Practical Example

const fields = ["name", "age", "city"];
const values = ["Alice", 25, "Paris"];

const person = {
  [fields[0]]: values[0],
  [fields[1]]: values[1],
  [fields[2]]: values[2]
};

console.log(person);  // { name: "Alice", age: 25, city: "Paris" }

Think of it like a form where both the label and the input are filled in programmatically—you're not hardcoding anything.

When This Matters

This pattern shines when you're transforming data, building objects from loops (in future lessons), or when key names and values come from external sources like APIs or user input.

Key Takeaway: You can use expressions for both computed property names (in brackets) and their values, giving you complete dynamic control over object creation.