![]() |
In TypeScript, objects are mutable, which means you can modify them by adding, updating, or removing properties. Removing a key from an object involves either creating a new object without the specified key or using certain built-in methods to achieve the desired result. Below are the approaches used to remove a key from TypeScript object: Table of Content Approach 1: Using spread operatorThis approach involves creating a new object that excludes the key you want to remove. The spread operator (…) is used to copy the existing properties of the object into a new object, excluding the specified key. Syntax:const modifiedObject = { ...originalObject, [keyToRemove]: undefined }; Example: In this example, year is removed from originalObject, and the result is stored in newObject.
Output: Original Object Approach 2: Using delete keywordTo remove a key from a TypeScript object, you can use the Syntax:delete objectName[keyToRemove]; Example: In this example, the age property is removed from the person object using the delete keyword.
Output: Original Object Approach 3: Using Object.assign()To remove a key from an object using Object.assign(), we create a new object by copying all properties from the original object except for the specified key. Example: In this example we creates a TypeScript object, removes a specified key using Object.assign() and delete, and logs both the original and modified objects. It’s correct but could benefit from using more TypeScript-friendly methods.
Output: Original Object: Approach 4: Using Object destructuring and rest syntaxIn this approach, we leverage object destructuring along with the rest syntax to create a new object that excludes the specified key. We use object destructuring to extract all properties of the original object except the one we want to remove, and then use the rest syntax to collect these properties into a new object. Example: In this example, we’ll use object destructuring and rest syntax to remove the key “year” from the original object.
Output Original Object: |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |