Skip to content

Instantly share code, notes, and snippets.

@IrvingArmenta
Last active July 14, 2023 04:06
Show Gist options
  • Save IrvingArmenta/dc322ff9792816e39efd8e83963b37d1 to your computer and use it in GitHub Desktop.
Save IrvingArmenta/dc322ff9792816e39efd8e83963b37d1 to your computer and use it in GitHub Desktop.
Pick and/or Reject Object data by keys
function pick<OriginalObj extends Record<string, unknown>, Keys extends Partial<keyof OriginalObj>>(
obj: Partial<OriginalObj>,
keys: Keys[]
) {
type ReturnObj = Record<Keys, OriginalObj[Keys]>;
return keys
.map(k => (k in obj ? { [k]: obj[k] } : {}))
.reduce((res, o) => Object.assign(res, o), {}) as ReturnObj;
}
function reject<
OriginalObj extends Record<string, unknown>,
Keys extends Partial<keyof OriginalObj>
>(obj: Partial<OriginalObj>, keys: Keys[]) {
type ReturnObj = Record<Exclude<keyof OriginalObj, Keys>, OriginalObj[Keys]>;
return Object.keys(obj)
.filter(k => !keys.includes(k as Keys))
.map(k => ({ [k]: obj[k] }))
.reduce((res, o) => Object.assign(res, o), {}) as ReturnObj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment