How to use Object.assign() In Typescript
Another method to remove keys from a TypeScript dictionary is by utilizing Object.assign(). This method creates a new object by merging properties from multiple objects, allowing us to exclude specific keys during the merging process.
Syntax:
Object.assign(target, ...sources);
Example: In this example we creates a dictionary, removes specified keys, and stores the updated dictionary. It then logs the updated dictionary.
let dict: { [key: string]: string } = {
"Java": "Programming Language",
"Python": "Scripting Language",
"C++": "Programming Language",
"JavaScript": "Scripting Language",
"TypeScript": "Programming Language",
};
const keysToRemove: string[] = ["Python", "JavaScript"];
const updatedDict = Object.assign({}, ...Object.keys(dict)
.filter(key => !keysToRemove.includes(key))
.map(key => ({ [key]: dict[key] })));
console.log("Updated Dictionary:");
console.log(updatedDict);
Output:
{
"Java": "Programming Language",
"C++": "Programming Language",
"TypeScript": "Programming Language"
}
How to Remove Keys from a TypeScript Dictionary ?
In TypeScript, we can remove keys from a TypeScript Dictionary using various approaches that include deleting keywords, Object Destructuring, and by using Object.keys() and Array.reduce() methods.
There are several approaches to removing keys from a TypeScript Dictionary which are as follows:
Table of Content
- Using delete Keyword
- Using Object Destructuring
- Using Object.keys() and Array.reduce() methods
- Using Object.assign()
Contact Us