Skip to content

Instantly share code, notes, and snippets.

@thadeu
Last active March 29, 2019 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thadeu/21edfa3c5873b359cf997975bab79034 to your computer and use it in GitHub Desktop.
Save thadeu/21edfa3c5873b359cf997975bab79034 to your computer and use it in GitHub Desktop.
export function deepOmit(obj, excludes) {
const result = {}
excludes = Array.isArray(excludes) ? excludes : [excludes]
for (let i in obj) {
if (Array.isArray(obj[i])) {
const nextValue = obj[i].map(arrItem => {
if (isObject(arrItem)) {
return deepOmit(arrItem, excludes)
}
return arrItem
})
result[i] = nextValue
} else if (!excludes.includes(i)) {
result[i] = obj[i]
}
}
// cache new object
for (let i in result) {
if (isObject(result[i])) {
result[i] = deepOmit(result[i], excludes)
}
}
return result
}
function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]'
}

How to use deepOmit?

  • with array
const obj = { username: 'foo', password: 'bar', __typename: 'User' }
const newObj = deepOmit({ username, password }, ['__typename'])
console.log(newObj) -> { username: 'foo', password: 'bar' }
  • simple prop
const obj = { username: 'foo', password: 'bar', __typename: 'User' }
const newObj = deepOmit({ username, password }, '__typename')
console.log(newObj) -> { username: 'foo', password: 'bar' }
  • deep prop
const obj = { username: 'foo', password: 'bar', other: { prop: 'test', __typename: 'User' } }
const newObj = deepOmit({ username, password }, ['__typename'])
console.log(newObj) -> { username: 'foo', password: 'bar', other: { prop: 'test' } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment