How to use Object.entries() and Array.find() In Typescript
In TypeScript, you can use Object.entries() to get an array of key-value pairs from an object. Then, you can use array methods like Array.find() to find the value associated with a specific key.
Example: In this example, we’ll use Object.entries() and Array.find() to get the value associated with the key “category” from the object obj.
const obj: { [key: string]: string } = {
name: "w3wiki",
category: "Programming",
language: "TypeScript",
};
const desiredKey = "category";
const value = Object.entries(obj).find(([key, val]) => key === desiredKey)?.[1];
console.log(value); // Logs "Programming"
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