Sub topic 4
Renaming Properties as You Destructure
This chapter assumes you know basic object destructuring (const { a } = obj) and default values in patterns. Both were covered in earlier chapters. Here you will learn how to bind a property to a variable whose name differs from the property's key.
The Syntax: `key: newName`
In an object pattern, source: target means "read the property source and store it in a variable called target."
const response = { status: 200, data: { items: [] } };
const { status: httpStatus, data: payload } = response;
console.log(httpStatus); // 200
console.log(payload); // { items: [] }The pattern looks like an object literal, but the direction is reversed. In a literal, { a: b } puts the value b into the key a. In a pattern, { a: b } takes the value of key a and puts it into b. The key always sits on the left.
Why Rename?
Renaming solves several everyday problems:
- Name collisions. You may destructure two objects that both have an
id, or a local variable may already use the name. - Unclear names. A key such as
dorvalreads better asdurationMsin your code. - Foreign conventions. APIs often return
snake_casekeys, and renaming converts them tocamelCase. - Keys that are not valid identifiers. A key like
'content-type'cannot be a variable name, so you must rename it.
const apiUser = { user_id: 42, 'first-name': 'Grace' };
const localUser = { user_id: 7 };
const { user_id: remoteId, 'first-name': firstName } = apiUser;
const { user_id: localId } = localUser;
console.log(remoteId, localId, firstName); // 42 7 'Grace'Renaming with a Default
You can rename a property and give it a default in the same pattern. The order is key: newName = default.
const config = { timeout: 3000 };
const { timeout: waitMs = 1000, retries: maxRetries = 3 } = config;
console.log(waitMs); // 3000 (property exists)
console.log(maxRetries); // 3 (property missing, default used)Computed Keys Require a Name
When the key is only known at runtime, use a computed key in brackets. A computed key has no identifier the engine could use as a variable name, so you must supply one.
const field = 'email';
const record = { email: '[email protected]' };
const { [field]: value } = record;
console.log(value); // '[email protected]'Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Writing `{ newName: key }` | Looks up a property called `newName`, which is usually undefined | Put the existing key on the left |
| Using the old name after renaming | `ReferenceError`, because only the new name is bound | Use the new name, or destructure the key twice |
| `{ = 5 timeout: t }` or `{ timeout = 5: t }` | `SyntaxError` | Write `{ timeout: t = 5 }` |
| `const { [key] } = obj` | `SyntaxError` | Add a target: `{ [key]: v }` |
The second error catches many people:
const { user_id: userId } = { user_id: 5 };
console.log(userId); // 5
try {
console.log(user_id);
} catch (err) {
console.log(err instanceof ReferenceError); // true
}You can destructure the same key more than once if you need it under two names: const { a, a: alsoA } = obj;.
Exercise
Given const point = { x: 4, 'z-index': 2 };, write one destructuring declaration that creates left from x, depth from 'z-index', and top from a missing property y, with top defaulting to 0.
Show answer
const { x: left, 'z-index': depth, y: top = 0 } = point; This gives left = 4, depth = 2, top = 0. The key comes before the colon, the new variable name comes after it, and the default comes after the new name.
Exercise
What does const { name: title } = { title: 'Dr', name: 'Ada' }; console.log(title); print, and why?
Show answer
It prints 'Ada'. The pattern reads the property name and stores its value in a variable called title. The object's own title property is ignored.