LoginSignup
40
31

More than 3 years have passed since last update.

JavaScript: オブジェクトからundefinedを取り除く関数

Posted at

JavaScriptのオブジェクトから、値がundefinedなフィールドを取り除く関数です。

オブジェクトからundefinedを取り除く関数

function removeUndefinedFromObject(object) {
  return Object.fromEntries(
    Object.entries(object).filter(([k, v]) => v !== undefined)
  )
}

実行例

console.log(
  removeUndefinedFromObject({
    a: undefined,
    b: 0,
    c: "",
    d: null,
    e: { e1: undefined, e2: 1 },
  })
)
//=> { b: 0, c: '', d: null, e: { e1: undefined, e2: 1 } }

注意事項

再帰的にはチェックしません

上の実行例で分かるように、ネストしたオブジェクトのプロパティはチェックされません。

対応バージョン

ES2017とES2019に未対応の環境では下記関数が動作しません:

  • Object.fromEntries - ES2019
  • Object.entries - ES2017

必要に応じてpolyfillを当てて下さい。

40
31
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40
31