flightcontrolhq / superjson

Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.
https://www.flightcontrol.dev?ref=superjson
MIT License
4.13k stars 91 forks source link

Delete undefined props? #220

Closed SrBrahma closed 1 year ago

SrBrahma commented 1 year ago

A common practice to deeply remove undefined properties from objects is to use JSON.parse(JSON.stringify(data));. I can't use it on my current situation as it would remove the types that superjson supports.

It's possible to somehow make superjson to remove undefined props to use it like JSON.parse(JSON.stringify(data));?

Skn0tt commented 1 year ago

Hi @SrBrahma! SuperJSON was designed to transmit JS values over the network, while keeping the object as similar as possible. It was originally motivated by Blitz's RPC mechanism, where the network layer is abstracted away from devs.

Part of that is to persist the difference between { foo: undefined } and {}, which behave differently when passed e.g. to Object.keys, Object.values or Object.entries.

If you want to remove undefined props from an object, I recommend you to either write a small traversal algorithm yourself, or to use something like deep-cleaner.

SrBrahma commented 1 year ago

My issue was originally with MongoDB, it was converting undefined props to null. Internally, it uses BSON. I discovered that Mongo has the ignoreUndefined option, that is later passed to the BSON serializer and removes them!