How to use Object.keys() and Array.prototype.map() In Typescript
In this approach we are using Object.keys() and Array.prototype.map() to iterate over dictionary keys, constructing an array of key-value pairs formatted as strings. This approach efficiently converts a TypeScript dictionary to a string representation.
Syntax:
function dictionaryToString(dictionary: Dictionary): string {
return Object.keys(dictionary)
.map(key => `${key}: ${dictionary[key]}`)
.join(', ');
}
Example: In this example we defines a function dictionaryToString to convert a TypeScript dictionary to a string using Object.keys() and Array.prototype.map(), then logs the result.
interface Dictionary {
[key: string]: string;
}
function dictionaryToString(dictionary: Dictionary): string {
return Object.keys(dictionary)
.map(key => `${key}: ${dictionary[key]}`)
.join(', ');
}
let dictionary: Dictionary = {
"name": "w3wiki",
"desc": "A computer science portal",
"est": "2009"
};
let dictString: string = dictionaryToString(dictionary);
console.log(dictString);
Output:
"name: w3wiki, desc: A computer science portal, est: 2009"
How to Convert Typescript Dictionary to String ?
In TypeScript, dictionaries are often represented as the objects where keys are associated with the specific values. Converting a TypeScript dictionary to a string is an important task usually when doing API calls where we cast the JSON response from the API to a string.
Below are the ways to convert a TypeScript dictionary to a string:
Table of Content
- Using JSON.stringify() method
- Using a custom function
- Using Object.keys() and Array.prototype.map()
Contact Us