Skip to content

Instantly share code, notes, and snippets.

@Billy-
Last active April 15, 2019 16:48
Show Gist options
  • Save Billy-/d94b65998501736bfe6521eadc1ab538 to your computer and use it in GitHub Desktop.
Save Billy-/d94b65998501736bfe6521eadc1ab538 to your computer and use it in GitHub Desktop.
deep version of lodash omit

Inspired by this issue on the lodash repo, asking for deep functionality for omit.

Note that there are plans to remove omit entirely in lodash v5... and props to this comment (and the one it quotes) in response to that 😆.

function omitDeep(value, key) {
if (Array.isArray(value)) {
return value.map(i => omitDeep(i, key))
}
else if (typeof value === 'object' && value !== null) {
return Object.keys(value)
.reduce(
(newObject, k) => {
if (k == key) return newObject
return Object.assign(
{ [k]: omitDeep(value[k], key) },
newObject
)
},
{}
)
}
return value
}
@iamdanthedev
Copy link

Thanks for quick solution

@iamdanthedev
Copy link

Important:
because of typeof null === 'object' line 8 should state:

      else if (typeof val === 'object' && val !== null) newObj[i] = omitDeep(val, key)

@Billy-
Copy link
Author

Billy- commented Dec 18, 2017

Thanks for catching that, I've updated the gist.

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