How to use Object.keys() Method In Typescript
In TypeScript, you can use the Object.keys()
method to get an array of the object’s own enumerable property names. Then, you can iterate over this array to find and access the value associated with a specific key.
Syntax:
Object.keys(obj).forEach(key => {
if (key === specificKey) {
let value = obj[key];
}
});
Example: In this example, we’ll use Object.keys() to get the value associated with the key “category” from the object obj.
let obj = { name: "w3wiki", category: "Programming", language: "TypeScript" };
let specificKey = "category";
let res: string | undefined;
Object.keys(obj).forEach(key => {
if (key === specificKey) {
res = obj[key];
}
});
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