Reflect Own Keys Enumerates Symbol Keys
Object.keys and JSON.stringify skip symbol keys, so cloning or auditing whole records needs Reflect.ownKeys, the only builtin that lists every own key.
Code
const visible = Symbol('visible');
const hidden = Symbol('hidden');
const record = {
id: 'a-1',
[visible]: 'meta',
[hidden]: 'secret',
};
// Object.keys 只报可枚举字符串键
console.log('Object.keys:', Object.keys(record));
// Object.getOwnPropertyNames:字符串键,含不可枚举
console.log('getOwnPropertyNames:', Object.getOwnPropertyNames(record));
// Reflect.ownKeys:字符串键 + Symbol 键的完整清单
console.log('Reflect.ownKeys:', Reflect.ownKeys(record));
// for...in 与 JSON 序列化同样跳过 Symbol
console.log('JSON:', JSON.stringify(record));
// 按 key 种类拆分处理:克隆/审计时 Symbol 载荷也要带上
const symbols = Reflect.ownKeys(record).filter((k) => typeof k === 'symbol');
console.log('symbol keys count:', symbols.length);Output
Captured from a sandboxed run of this snippet in the build pipeline.
Object.keys: [ 'id' ]
getOwnPropertyNames: [ 'id' ]
Reflect.ownKeys: [ 'id', Symbol(visible), Symbol(hidden) ]
JSON: {"id":"a-1"}
symbol keys count: 2Three key listings
Object.keys(record) returns only enumerable string keys (id); Object.getOwnPropertyNames returns all string keys; Reflect.ownKeys returns strings and symbols together — the only builtin of the three that lists [visible] and [hidden].
Serialization skips symbols
JSON.stringify(record) prints just {“id”:“a-1”} because for…in and JSON both ignore symbol keys; anything stored under a symbol silently vanishes from a payload.
Splitting by key kind
The audit step filters Reflect.ownKeys(record) with typeof k === ‘symbol’ and reports symbol keys count: 2 — the basis for a clone or audit that must carry symbol-keyed data along.
Interactive Tools for This Topic
FAQ
- Why does JSON.stringify drop symbol-keyed data?
- JSON serialization only covers string keys, so any value stored under a Symbol is invisible to it and to for...in enumeration.
- Which builtin lists every own key?
- Reflect.ownKeys — strings and symbols, enumerable or not; Object.keys (enumerable strings) and getOwnPropertyNames (all strings) are subsets.
Report a problem with this exampleOpens a pre-filled issue on GitHub.