how to check if a key is in the Object

kazoottt

KazooTTT

Posted on May 6, 2024

how to check if a key is in the Object

there are many methods.

in operator

in - JavaScript | MDN

The in operator returns true if the specified property is in the specified object or its prototype chain.

how to use?

for example:

const dict = { a: "a", b: "b" }
console.log("a" in dict)
Enter fullscreen mode Exit fullscreen mode

attention: the attribute name should be string.

that is to say:

  • a in dict ❎
  • "a" in dict ✅

Object API: hasOwnProperty

Object.prototype.hasOwnProperty() - JavaScript | MDN

The complete expression is Object.prototype.hasOwnProperty().

how to use it ?

const dict = {
  a: "a",
  b: "b",
}
console.log(dict.hasOwnProperty("a"))
Enter fullscreen mode Exit fullscreen mode

the same is the attribute key should be a string.

  • a in dict ❎
  • "a" in dict ✅
💖 💪 🙅 🚩
kazoottt
KazooTTT

Posted on May 6, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related