How to use Object.keys method In Typescript

A common approach to transform a TypeScript dictionary into an array involves utilizing Object.keys(), which provides an array comprising the enumerable property name of the given object.

Syntax:

Object.keys(obj);  // It will return the array of all keys.

Example: The below code uses `keys()` method to convert the dictionary into an array using TypeScript.

Javascript
// Creating a dictionary object
const dictionary = {
    name: "Hritik",
    email: "gfg@gmail.com",
    isActive: true,
    mobile: 9876543210,
}

// Fetch the all keys from the dictionary as an array
const allKeys = Object.keys(dictionary);

console.log("Here, We have array of all keys:");
console.log(allKeys);

Output
Here, We have array of all keys:
[ 'name', 'email', 'isActive', 'mobile' ]

How to Convert a Dictionary to an Array in TypeScript ?

In TypeScript, converting a dictionary(an object) into an Array can be useful in scenarios where you need to work with the values in a more iterable and flexible manner.

These are the following approaches:

Table of Content

  • Using Object.keys method
  • Using Object.values method
  • Using Object.entries method
  • Using Object.getOwnPropertyNames

Similar Reads

Using Object.keys method

A common approach to transform a TypeScript dictionary into an array involves utilizing Object.keys(), which provides an array comprising the enumerable property name of the given object....

Using Object.values method

A common approach to transform a TypeScript dictionary into an array involves utilizing Object.entries(), which provides an array comprising the values of the given object....

Using Object.entries method

When both keys and values are required in the form of an array, the Object.entries() method comes in handy. This method fetches both keys and values from the dictionary, allowing us to convert them into an array of objects or an array of arrays based on our specific needs....

Using Object.getOwnPropertyNames

In this approach we are using `Object.getOwnPropertyNames()` to retrieve an array containing all property names of an object. It includes non-enumerable properties and returns them as an array for further processing or analysis....

Contact Us