Destructuring Digs Nested Paths and Renames
Pull deep fields out in one statement with nested destructuring, rename bindings with colons, and combine defaults so missing API data cannot crash a render.
Code
// 嵌套解构:从深层结构直接取出字段
const response = {
data: { user: { name: "Ada", role: "admin" } },
meta: { page: 1 }
};
const { data: { user: { name, role } }, meta: { page } } = response;
console.log(name, role, page);
// 重命名:冒号语法把字段绑定到新变量名
const { data: { user: { name: userName } } } = response;
console.log("renamed:", userName);
// 数组嵌套:跳过不需要的元素
const [first, , [inner]] = [1, 2, [3, 4]];
console.log(first, inner);
// 默认值 + 重命名同时使用
const { status = "ok" } = {};
console.log("default:", status);
// 函数参数解构 + 默认值
function render({ title = "untitled", tags = [] } = {}) {
return `${title} (${tags.length} tags)`;
}
console.log(render({ title: "post", tags: ["a"] }));
console.log(render());Output
Captured from a sandboxed run of this snippet in the build pipeline.
Ada admin 1
renamed: Ada
1 3
default: ok
post (1 tags)
untitled (0 tags)How it works
The only function declaration is render, whose parameter is destructured with defaults.
What to watch for
- Zero-fetch snippet: every identifier resolves inside the language distribution.
Using it
The entry-point signature is function render({ title = "untitled", tags = [] } = {})
Output lines are prefixed (renamed:, default:), making each step’s effect easy to spot.
Key statements
return `${title} (${tags.length} tags)`;
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. The file defines `render` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.