Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 282
Nick Heiner Avatar asked May 18 '16 18:05

Nick Heiner


People also ask

How do you check if an object has any keys JS?

There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.

How do I get a list of keys from an object?

For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.

How do you check if all object keys has value?

To check if all of the values in an object are equal, use the Object. values() method to get an array of the object's values and call the every method on the array. On each iteration, check if the current value is equal to the value at index 0 of the array and return the result. Copied!


1 Answers

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.

like image 81
apsillers Avatar answered Oct 13 '22 20:10

apsillers