How to use Object.hasOwnProperty() Method In Typescript
This method checks if an object contains a specified property as its own property, and if it does, retrieves the corresponding value. It’s particularly useful when you want to ensure that the property exists before accessing its value.
Syntax:
if (obj.hasOwnProperty(key)) {
let value = obj[key];
}
Example: In this example we retrieves the value associated with the key ‘category’ from the object obj and logs it to the console.
const obj: { [key: string]: string } = {
name: "w3wiki",
category: "Programming",
language: "TypeScript",
};
if (obj.hasOwnProperty('category')) {
const res: string = obj['category'];
console.log(res);
}
Output:
Programming
How to Get an Object Value By Key in TypeScript
In TypeScript, we can get an object value by key by accessing the specific properties within the objects of the dynamic type. This can be done using Dot Notation, Bracket Notation, and Optional Chaining. In this article, we will explore all these approaches along with their implementation in terms of examples and outputs.
Table of Content
- Using Dot Notation
- Using Bracket Notation
- Using Optional Chaining
- Using Object.hasOwnProperty() Method
- Using Object.entries() and Array.find()
- Using Object.keys() Method
Contact Us