How to useObject.entries() and map method in Typescript
Here we use the Object.entries() method to retrieve an array of ‘[key, value]’ pairs from the object, and then uses the map method to create a typed array by extracting the values.
Syntax:
const newArray: string[] = Object.entries(obj).map(([key, value]) => value);
Example: The below code explains the use of Object.entries() and map method to create a typed array from an object with keys in Typescript.
const arr = {
name: "w3wiki",
category: "Programming",
founded: 2009,
};
const typeArr: (string | number)[] = Object
.entries(arr).map(([key, value]) => value);
console.log(typeArr);
Output:
["w3wiki", "Programming", 2009]
How to Create a Typed Array from an Object with Keys in TypeScript?
In TypeScript, we can create a typed array from an object with keys by extracting the keys and then mapping them to the desired array type. This mainly makes sure that type of safety is preserved.
Below are the approaches used to create a Typed Array from an Object with Keys in TypeScript:
Table of Content
- Using Object.keys() and map method
- Using Object.entries() and map method
- Using Object.getOwnPropertyNames() method