Skip to content

Instantly share code, notes, and snippets.

@negibouze
Last active November 23, 2020 07:59
Show Gist options
  • Save negibouze/6df792fef24e2e9c50a27686c3bd2748 to your computer and use it in GitHub Desktop.
Save negibouze/6df792fef24e2e9c50a27686c3bd2748 to your computer and use it in GitHub Desktop.
Remove null value or convert to undefined.
type RemoveNull = {
(x: null): undefined
<T> (x: T): T
<T> (x: T[]): T[]
}
/**
* null を取り除く
* x が null の場合は undefined を返す
* x が Array の場合は null を undefined に変換した Array を返す
* x が Object の場合は 値が null のプロパティを削除した Object を返す
*
* @param x: 値
* @example
* removeNull(null) //=> undefined
* @example
* removeNull([1, undefined, 'foo', null]) //=> [1, undefined, 'foo', undefined]
* @example
* removeNull({ foo: undefined, bar: null }) //=> { foo: undefined }
* @example
* removeNull([
* {
* bar: '',
* baz: null,
* qux: 10,
* quux: {
* corge: 'aiueo',
* grault: 100,
* garply: null,
* waldo: {
* fred: null,
* plugh: undefined,
* xyzzy: 1000,
* thud: 'kakikukeko'
* }
* }
* },
* ])
* //=> [
* {
* bar: '',
* qux: 10,
* quux: {
* corge: 'aiueo',
* grault: 100,
* waldo: {
* plugh: undefined,
* xyzzy: 1000,
* thud: 'kakikukeko'
* }
* }
* },
* ]
*/
export const removeNull: RemoveNull = (x: any) => {
if (x === null) {
return undefined
}
if (Array.isArray(x)) {
return x.map(x => removeNull(x))
}
if (typeof x === 'object') {
return Object.fromEntries(
Object.entries(x).filter(([_, v]) => v !== null).map(([k, v]) => [k, removeNull(v)])
)
}
return x
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment