Last active
July 14, 2023 04:06
-
-
Save IrvingArmenta/dc322ff9792816e39efd8e83963b37d1 to your computer and use it in GitHub Desktop.
Pick and/or Reject Object data by keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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