Nick Heiner
Nick Heiner

Reputation: 122550

See all keys of a JS object, even those defined by getters

I would like to JSON.stringify all properties of an object, including those defined via getters. However, when I call JSON.stringify on an object, properties defined via getters are omitted:

> const obj = {key: 'val'}
undefined

> JSON.stringify(obj)
'{"key":"val"}'

> Object.defineProperty(obj, 'getter', {get: () => 'from getter'})
{ key: 'val' }

> obj.getter
'from getter'

> JSON.stringify(obj)
'{"key":"val"}'

I was hoping to see:

> JSON.stringify(obj)
'{"key":"val", "getter": "from getter"}'

Is this possible? Object.keys isn't detecting the getters either:

> Object.keys(obj)
[ 'key' ]

Can you query for getter keys? Or do you have to know their names ahead of time?

Upvotes: 7

Views: 2628

Answers (1)

apsillers
apsillers

Reputation: 115980

JSON.stringify only includes enumerable properties in its output.

When enumerable is not specified on the property descriptor passed into Object.defineProperty, it defaults to enumerable: false. Thus, any property definition done by Object.defineProperty (with a getter or not) will be non-enumerable unless you explicitly specify enumerable: true.

You can get all the properties that exist on an object (N.B: not inherited properties) with Object.getOwnPropertyNames or (in ES2015+) Reflect.ownKeys. (The only difference between these is that Reflect.ownKeys also includes properties defined by a Symbol key.) It is not possible to make JSON.stringify include non-enumerable properties; you must instead make the property enumerable.

Upvotes: 6

Related Questions