Skip to content

Instantly share code, notes, and snippets.

@sahara-ooga
Last active February 11, 2018 06:46
Show Gist options
  • Save sahara-ooga/e3fe250151601c4f0f19eaba00cd0599 to your computer and use it in GitHub Desktop.
Save sahara-ooga/e3fe250151601c4f0f19eaba00cd0599 to your computer and use it in GitHub Desktop.
JavaScriptのオブジェクトで、指定したキーの値が無かったときのハンドリング
const jsonObject = { "users" : {
"21532761536" : {
"user_id" : 21532761536,
"name" : "Tom Hanks",
}
}
}
const sender_id = "hhh";
const result = jsonObject.users[sender_id];
//もし、存在しないキーを指定した場合、undefinedが返る
console.log(result) //undefined
//undefinedであることを判定する
console.log(result === undefined) //true

JavaScriptのオブジェクトで、指定したキーの値が無かったときのハンドリング

例として、次のようなオブジェクトの構造を考える:

const jsonObject = { "users" : {
    "21532761536" : {
      "user_id" : 21532761536,
      "name" : "Tom Hanks",
      }
  }
}

jsonObject.users["hhh"] を指定すると、undefinedが返る。

undefinedが返ってくることを検出するには、

result === undefined

とすればBool値で返ってくる。

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