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?
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.
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With