How to use for loop In Typescript
In this approach we iterate over the keys of the dictionary using for loop and compare each key with the key we searching for.
Example: The below code uses the for loop to check if a key exists in dictionary in TypeScript.
Syntax:
for (let key in dict) {
if (key === keyToFind) {
keyExists = true;
}
interface Dictionary {
[key: string]: any;
}
const dict: Dictionary = {
org: 'w3wiki',
founder: 'Sandeep Jain' };
let keyToFind = 'org';
let keyExists = false;
for (let key in dict) {
if (key === keyToFind) {
keyExists = true;
break;
}
}
if (keyExists) {
console.log('Key ' + keyToFind + ' exists in the dictionary.');
} else {
console.log('Key ' + keyToFind + ' does not exist in the dictionary.');
}
Output:
Key org exists in the dictionary.
How to Check if a Key Exists in a Dictionary in TypeScript ?
In TypeScript dictionaries are used whenever the data is needed to be stored in key and value form. We often retrieve the data from the dictionaries using an associated key. Therefore it becomes crucial to check whether the key exists in a dictionary or not.
We can use the below methods to check if a key exists or not in a dictionary.
Table of Content
- Using an ‘in’ operator
- Using the hasOwnProperty method
- Using the undefined keyword
- Using the Map object
- Using for loop