Recursively omit keys from an object by defining an array of exclusive keys in ES6 + Typcript.
omitDeep(myObject, [omitKey1, omitKey2,...omitKeyN])
// omitDeep.ts /** * Recursively remove keys from an object * @usage * * const input = { * id: 1, * __typename: '123', * createdAt: '1020209', * address: { * id: 1, * __typename: '123', * }, * variants: [ * 20, * { * id: 22, * title: 'hello world', * __typename: '123', * createdAt: '1020209', * variantOption: { * id: 1, * __typename: '123', * }, * }, * { * id: 32, * __typename: '123', * createdAt: '1020209', * }, * ], * } * * const output = { * id: 1, * address: { * id: 1, * }, * variants: [ * 20, * { * id: 22, * title: 'hello world', * variantOption: { * id: 1, * }, * }, * { * id: 32, * }, * ], * } * * expect(omitDeep(input, ['createdAt, 'updatedAt', __typename']).to.deep.equal(output) // true * * @param {object} input * @param {Array<number | string>>} excludes * @return {object} */ const omitDeep = (input: object, excludes: Array<number | string>): object => { return Object.entries(input).reduce((nextInput, [key, value]) => { const shouldExclude = excludes.includes(key) if (shouldExclude) return nextInput if (Array.isArray(value)) { const arrValue = value const nextValue = arrValue.map((arrItem) => { if (typeof arrItem === 'object') { return omitDeep(arrItem, excludes) } return arrItem }) nextInput[key] = nextValue return nextInput } else if (typeof value === 'object') { nextInput[key] = omitDeep(value, excludes) return nextInput } nextInput[key] = value return nextInput }, {}) } export default omitDeep