How to use Object.entries method In Typescript
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.
Syntax:
Object.entries(obj)
// The method returns an array of array containing key, value pairs
Example: The below code uses `entries()` methods to convert the dictionary into an array using TypeScript.
// Creating a dictionary object
const dictionary = {
name: "Hritik",
email: "gfg@gmail.com",
isActive: true,
mobile: 9876543210,
}
// Now, converting the dictionary object into an array
const arrOfArr = Object.entries(dictionary);
console.log("Converting an object into an array of arrays");
console.log(arrOfArr);
Output
Converting an object into an array of arrays [ [ 'name', 'Hritik' ], [ 'email', 'gfg@gmail.com' ], [ 'isActive', true ], [ 'mobile', 9876543210 ] ]
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
Contact Us