How to use Associative Array in TypeScript ?
Last Updated :
05 Apr, 2024
Typescript Associative arrays are objects in which indexes are replaced by user-defined keys. Associative Array can be used like a regular array, but the only difference is that it can be accessed using strings instead of numbers.
Syntax:
let associativeArray: { [key: string]: string } = {
key1: "value1",
key2: "value2",
};
console.log(associativeArray['key1']);
// Output: value1
Example 1: To demonstrate creating and accessing values in an associative array using TypeScript.
JavaScript
let fruitMap:
{
[key: string]: string
} =
{
"apple": "red",
"banana": "yellow",
"grapes": "green"
};
// Adding elements to the associative array
fruitMap["orange"] = "orange";
// Printing the keys of the associative array
console.log("Keys are listed below:");
console.log(Object.keys(fruitMap));
// Accessing values using keys
console.log("Color of apple:", fruitMap["apple"]);
console.log("Color of banana:", fruitMap["banana"]);
console.log("Color of grapes:", fruitMap["grapes"]);
console.log("Color of orange:", fruitMap["orange"]);
Output:
Keys are listed below:
[ 'apple', 'banana', 'grapes', 'orange' ]
Color of apple: red
Color of banana: yellow
Color of grapes: green
Color of orange: orange
Example 2: To demonstrate iterating over keys and values in an associative array in TypeScript.
JavaScript
let fruitMap:
{
[key: string]: string
} =
{
"apple": "red",
"banana": "yellow",
"grapes": "green"
};
// Adding elements to the associative array
fruitMap["orange"] = "orange";
// Iterating over keys and
// values in the associative array
console.log("Iterating over keys and values:");
for (let key in fruitMap) {
if (fruitMap.hasOwnProperty(key)) {
console.log("Key:", key, ", Value:", fruitMap[key]);
}
}
Output:
Iterating over keys and values:
Key: apple , Value: red
Key: banana , Value: yellow
Key: grapes , Value: green
Key: orange , Value: orange
Example 3: To demonstrate removing an element from an associative array in TypeScript.
JavaScript
// Creating an associative
//array (object) in TypeScript
let fruitMap: { [key: string]: string } =
{
"apple": "red",
"banana": "yellow",
"grapes": "green"
};
// Removing an element
// from the associative array
delete fruitMap["grapes"];
console.log("After removing 'grapes':",
Object.keys(fruitMap));
Output:
After removing 'grapes': [ 'apple', 'banana' ]
Share your thoughts in the comments
Please Login to comment...