An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
Two Ways to Check an Object for Keys
The Old Way
Object.prototype.hasOwnProperty()
Object.prototype.hasOwnProperty()
is called on an object with the key (or property) for which you are checking passed in as an argument. This returns true if the property exists or false if not.
Note: this only checks for declared or own properties. Inherited properties will also return false.
const obj1 = { name: "Sam", age: 25,},obj1.hasOwnProperty("name") // => trueobj1.hasOwnProperty("address")// => false
Gotchas
One drawback to this method is that it is not accessible on an object created with Object.create(null)
and will error in that case:
The Recommended Way
Object.hasOwn()
Per MDN, Object.hasOwn()
is a replacement for the previously existing .hasOwnProperty
method. It is nearly identical to .hasOwnProperty
- it returns true if the object has the property as an own property and false for inherited properties as well as properties that do not exist.
const obj2 = { name: "Tim", age: 10,}Object.hasOwn(obj2, "name");// => trueObject.hasOwn(obj2, "address");// => false
However, .hasOwn
also works on objects created with Object.create(null)
and therefore is recommended for use on all browsers that support it:
Original Link: https://dev.to/smilesforgood/two-ways-to-check-an-object-for-keys-h2m
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To