How to Convert a Dictionary to an Array in TypeScript ?
Last Updated :
05 Mar, 2024
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:
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.
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
const dictionary = {
name: "Hritik" ,
email: "gfg@gmail.com" ,
isActive: true ,
mobile: 9876543210,
}
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' ]
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.
Syntax:
Object.values(obj); // It will return the array of all values.
Example: The below code uses `values()` method to convert the dictionary into an array using TypeScript.
Javascript
const dictionary = {
name: "Hritik" ,
email: "gfg@gmail.com" ,
isActive: true ,
mobile: 9876543210,
}
const allValues = Object.values(dictionary);
console.log( "Here, We have array of all values:" );
console.log(allValues);
|
Output
Here, We have array of all values:
[ 'Hritik', 'gfg@gmail.com', true, 9876543210 ]
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.
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.
Javascript
const dictionary = {
name: "Hritik" ,
email: "gfg@gmail.com" ,
isActive: true ,
mobile: 9876543210,
}
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 ]
]
Share your thoughts in the comments
Please Login to comment...