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.

Javascript
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

Similar Reads

Approach 1: Using Object.keys() and map method

Here we use the Object.key() method to extract an array of keys from the object and by using the map() method to create a typed array by accessing the values using keys....

Approach 2: Using Object.entries() and map method

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....

Approach 3: Using Object.getOwnPropertyNames() method

Here we use the Object.getOwnPropertyNames() method to get an array of all property names from the object and then the map method creates a typed array by accessing the corresponding values through the property names....

Using Object.values() Method

The Object.values() method returns an array of a given object’s own enumerable property values. We can utilize this method to directly extract the values of the object and create a typed array from them....