Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Object._trim(obj) to remove undefined values #39

Open
coolaj86 opened this issue Aug 31, 2022 · 0 comments
Open

Object._trim(obj) to remove undefined values #39

coolaj86 opened this issue Aug 31, 2022 · 0 comments
Labels
std Extends the Standard Library

Comments

@coolaj86
Copy link
Collaborator

coolaj86 commented Aug 31, 2022

var x = {
  foo: undefined,
  bar: undefined,
  baz: undefined,
  qux: 'quux',
};

var y = Object._trim(x);
// { qux: 'quux' }

Rationalé

Depending on how the rest of the language is implemented, this may not be necessary.

However, often times you'll want and expect undefined values to be ignored, but instead they get stringified or cause an error, such as with:

  • new URLSearchParams({ foo: undefined, bar: 'baz' }) // foo=undefined&bar=baz
  • db.query({ id: undefined, username: 'coolaj86' })

Considerations

This has to be implemented with care to keep type safety and to not break JIT optimizations.

For example:

  • delete may convert an optimized struct instance into an unoptimized key-value map
  • JSON.stringify will convert Dates to strings

Option A

Object._trim = function (obj) {
    let copied = {};
    for (let k in obj) {
        if ('undefined' !== typeof obj[k]) {
            copied[k] = obj[k];
        }
    }
    return copied;
}

Option B

Object._trim = function (obj) {
    for (let k in obj) {
        if ('undefined' === typeof obj[k]) {
            delete obj[k];
        }
    }
    return obj;
}
@coolaj86 coolaj86 added the std Extends the Standard Library label Aug 31, 2022
@coolaj86 coolaj86 changed the title Object._trim(obj) to remove undefined keys Object._trim(obj) to remove undefined values Aug 31, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
std Extends the Standard Library
Projects
None yet
Development

No branches or pull requests

1 participant