find if value exists in object in javascript

There are a couple of ways to check if a value exists in an object in JavaScript:

  1. Using the hasOwnProperty method: This method checks whether the object has a property with the specified name.
index.tsx
const obj = { name: "John", age: 30 };
if (obj.hasOwnProperty("name")) {
  console.log("Name exists in obj");
}
112 chars
5 lines
  1. Using the in operator: This operator checks whether the specified property is in the specified object or its prototype chain.
index.tsx
const obj = { name: "John", age: 30 };
if ("name" in obj) {
  console.log("Name exists in obj");
}
99 chars
5 lines
  1. Using the Array.prototype.includes method: This method checks whether the specified value is in the array of object property names.
index.tsx
const obj = { name: "John", age: 30 };
if (Object.keys(obj).includes("name")) {
  console.log("Name exists in obj");
}
119 chars
5 lines

gistlibby LogSnag