Computed property names
Wrap an expression in square brackets to use its value as the key.
const field = "email";
const user = {
name: "Maya",
[field]: "maya@example.com"
};
console.log(user); // → { name: Maya, email: maya@example.com }
Any expression works:
const id = 7;
const lookup = { ["user_" + id]: "Maya", [`${id}-label`]: "seven" };
console.log(lookup); // → { user_7: Maya, 7-label: seven }
Why it is useful: dynamic keys
Updating a form field by its name:
function setField(state, name, value) {
return { ...state, [name]: value };
}
let form = { email: "", name: "" };
form = setField(form, "email", "maya@example.com");
console.log(form); // → { email: maya@example.com, name: }
Counting words:
const counts = {};
for (const word of ["a", "b", "a"]) {
counts[word] = (counts[word] ?? 0) + 1;
}
console.log(counts); // → { a: 2, b: 1 }
Shorthand properties
When a variable name equals the key, write it once.
const title = "Hello";
const views = 120;
const post = { title, views };
console.log(post); // → { title: Hello, views: 120 }
Shorthand methods
const calculator = {
add(a, b) { return a + b; } // same as add: function (a, b) { ... }
};
Putting it together
function createProduct(name, price) {
return {
name,
price,
describe() {
return `${this.name}: $${this.price}`;
}
};
}
console.log(createProduct("Pen", 2).describe()); // → Pen: $2