Skip to content

Instantly share code, notes, and snippets.

@bisubus
Last active April 13, 2024 21:03
Show Gist options
  • Save bisubus/2da8af7e801ffd813fab7ac221aa7afc to your computer and use it in GitHub Desktop.
Save bisubus/2da8af7e801ffd813fab7ac221aa7afc to your computer and use it in GitHub Desktop.
ES5/ES6/ES2017/ES2019 omit & pick
Object.keys(obj)
.filter((key) => ['blacklisted', 'keys'].indexOf(key) < 0)
.reduce((newObj, key) => Object.assign(newObj, { [key]: obj[key] }), {})
Object.entries(obj)
.filter(([key]) => !['blacklisted', 'keys'].includes(key))
.reduce((obj, [key, val]) => Object.assign(obj, { [key]: val }), {});
Object.fromEntries(
Object.entries(obj)
.filter(([key]) => !['blacklisted', 'keys'].includes(key))
);
Object.keys(obj)
.filter((key) => ['whitelisted', 'keys'].indexOf(key) >= 0)
.reduce((newObj, key) => Object.assign(newObj, { [key]: obj[key] }), {})
Object.entries(obj)
.filter(([key]) => ['whitelisted', 'keys'].includes(key))
.reduce((obj, [key, val]) => Object.assign(obj, { [key]: val }), {});
Object.fromEntries(
Object.entries(obj)
.filter(([key]) => ['whitelisted', 'keys'].includes(key))
);
@ajitsinghkamal
Copy link

ajitsinghkamal commented Jan 20, 2022

Another solution to pick

const pick = <T extends object, K extends keyof T>(
    whitelisted: K[],
    target: T,
    defaultValue?: any
) =>
    Object.fromEntries(
        whitelisted.map((key) =>
            [ key, key in target ? target[key] : defaultValue ]
        )
    );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment