Computed Keys Build Objects Dynamically
Computed property keys turn variables and expressions into literal keys, building index tables and reading names that dot syntax cannot express.
Code
// 计算属性键:字面量里用方括号把变量变成键名
const field = 'email';
const record = { [field]: 'a@b.c', ['user_' + field]: 'x' };
console.log('keys:', Object.keys(record).join(','));
// 动态建索引:一次遍历把数组折叠成按 id 查找的表
const users = [
{ id: 'u1', name: 'Ada' },
{ id: 'u2', name: 'Ben' },
];
const byId = {};
for (const u of users) {
byId[u.id] = u;
}
console.log('byId.u2:', byId.u2.name);
// 键名含空格或符号时,方括号是唯一读写方式
const odd = { 'order total': 42, 'a-b': 1 };
console.log('bracket read:', odd['order total'], odd['a-b']);
// 方法名可以计算,Symbol 键同样支持
const secret = Symbol('secret');
const box = {
['get' + 'Value']() {
return 7;
},
[secret]: 'hidden',
};
console.log('computed method:', box.getValue(), '| symbol:', box[secret]);Output
Captured from a sandboxed run of this snippet in the build pipeline.
keys: email,user_email
byId.u2: Ben
bracket read: 42 1
computed method: 7 | symbol: hiddenHow the snippet works
The loop for (const u of users) is the only repeated construct.
The state lives in top-level bindings: field, record, users, byId.
Caveats
- The whole dependency story is the language version itself.
Using it
Look for the keys:, byId.u2:, bracket read: prefixes when the file runs; they tie each line to its step.
Key statements
const record = { [field]: 'a@b.c', ['user_' + field]: 'x' };
const odd = { 'order total': 42, 'a-b': 1 };
const secret = Symbol('secret');
Interactive Tools for This Topic
Bracket BalancerCheck whether parentheses, square brackets, and braces are balanced, reporting mismatches and maximum nesting depth.Email Address ValidatorValidate email syntax, checking the local part, domain labels, and top-level domain against common rules.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. Its state lives in module-level bindings: `field`, `record`, `users`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.