How to Remove a Key from TypeScript Object ?
Last Updated :
14 Aug, 2024
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 a TypeScript object:
Approach 1: Using spread operator
This 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.
JavaScript
interface MyObject {
[key: string]: any;
}
const originalObject: MyObject =
{ name: 'GFG', year: 2024, city: 'Noida' };
console.log("Original Object");
console.log(originalObject);
const keyToRemove: string = 'year';
console.log("After key removal");
const { [keyToRemove]: removedKey, ...newObject } =
originalObject;
console.log(newObject);
Output:
Original Object
{ name: 'GFG', year: 2024, city: 'Noida' }
After key removal
{ name: 'GFG', city: 'Noida' }
Approach 2: Using delete keyword
To remove a key from a TypeScript object, you can use the delete
operator or create a new object without the specified key.
Syntax:
delete objectName[keyToRemove];
Example: In this example, the age property is removed from the person object using the delete keyword.
JavaScript
interface Person {
name: string;
age: number;
city: string;
}
const person: Person =
{ name: 'Alice', age: 30, city: 'London' };
// Ensuring keyToRemove is a valid key of Person
const keyToRemove: keyof Person = 'age';
console.log("Original Object");
console.log(person);
// Deleting the specified key from the object
delete person[keyToRemove];
console.log("After key removal");
console.log(person);
Output:
Original Object
{ name: 'Alice', age: 30, city: 'London' }
After key removal
{ name: 'Alice', city: 'London' }
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.
JavaScript
interface MyObject {
[key: string]: any;
}
const originalObject: MyObject = { name: 'GFG', year: 2024, city: 'Noida' };
console.log("Original Object:");
console.log(originalObject);
const keyToRemove: string = 'year';
// Create a new object without the specified key
const newObject = Object.assign({}, originalObject);
delete newObject[keyToRemove];
console.log("After key removal:");
console.log(newObject);
Output:
Original Object:
{ name: 'GFG', year: 2024, city: 'Noida' }
After key removal:
{ name: 'GFG', city: 'Noida' }
Approach 4: Using Object destructuring and rest syntax
In 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.
JavaScript
interface MyObject {
[key: string]: any;
}
const originalObject: MyObject = { name: 'GFG', year: 2024, city: 'Noida' };
console.log("Original Object:");
console.log(originalObject);
const keyToRemove: string = 'year';
// Using object destructuring and rest syntax to remove the specified key
const { [keyToRemove]: removedKey, ...newObject } = originalObject;
console.log("After key removal:");
console.log(newObject);
Output
Original Object:
{ name: 'GFG', year: 2024, city: 'Noida' }
After key removal:
{ name: 'GFG', city: 'Noida' }
Approach 5: Using Object.entries() and Object.fromEntries()
This approach involves converting the object into an array of key-value pairs using Object.entries(), filtering out the key you want to remove, and then converting the array back into an object using Object.fromEntries(). This method is useful for creating a new object without modifying the original object.
Syntax:
const modifiedObject = Object.fromEntries(Object.entries(originalObject).filter(([key]) => key !== keyToRemove));
Example: In this example, the key year is removed from originalObject, and the result is stored in newObject.
JavaScript
interface MyObject {
[key: string]: any;
}
const originalObject: MyObject = { name: 'GFG', year: 2024, city: 'Noida' };
console.log("Original Object:");
console.log(originalObject);
const keyToRemove: string = 'year';
// Using Object.entries and Object.fromEntries to remove the specified key
const newObject = Object.fromEntries(Object.entries(originalObject).filter(([key]) => key !== keyToRemove));
console.log("After key removal:");
console.log(newObject);
OutputOriginal Object:
{ name: 'GFG', year: 2024, city: 'Noida' }
After key removal:
{ name: 'GFG', city: 'Noida' }
Similar Reads
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
3 min read
How to Sort or Reduce an Object by Key in TypeScript ?
Sorting an object by key generally refers to arranging its properties in a specific order, while reducing involves selecting a subset of properties based on provided keys. Different approaches allow developers to perform these operations with flexibility. Below are the approaches used to sort or red
3 min read
How to Remove Focus from Input Field in TypeScript ?
Removing the focus from an input field is a common requirement in web development. This can be useful in scenarios like form validation, user interactions, or controlling focus behavior. The below approaches can be used to achieve this task in TypeScript: Table of Content Using the blur() methodSett
3 min read
How to Remove Duplicates from an Array of Objects using TypeScript ?
We are given an array of objects and we have to check if there are duplicate objects present in the array and remove the duplicate occurrences from it. Otherwise, return the array as it is. Examples of Removing Duplicates from an Array of Objects using TypeScript Table of Content Using filter() and
4 min read
How to Get an Object Value By Key in TypeScript
In TypeScript, we can get an object value by key by accessing the specific properties within the objects of the dynamic type. This can be done using Dot Notation, Bracket Notation, and Optional Chaining. In this article, we will explore all these approaches along with their implementation in terms o
5 min read
How to remove a key-value pair from JavaScript object?
Removing a key-value pair from an object in JavaScript means deleting a specific property and its corresponding value from the object. This can be achieved using the delete operator, destructuring with the rest operator, or various utility functions to manipulate the object dynamically. There are se
3 min read
How to Check the Type of an Object in Typescript ?
When working with TypeScript, understanding how to check the type of an object is crucial for ensuring type safety and maintaining code integrity. TypeScript, being a statically typed superset of JavaScript, provides several approaches to accomplish this task as listed below. Table of Content Using
3 min read
How do I Remove an Array Item in TypeScript?
In this article, we will learn about the different ways of removing an item from an array in TypeScript. In TypeScript, an array can be defined using union typing if it contains items of different types. We can use the following methods to remove items from a TypeScript array: Table of Content Using
5 min read
TypeScript Object The Array Type
In TypeScript, the Array Type is used to specify and enforce the type of elements that can be stored in an array, enhancing type safety during development. This adaptability ensures reusability across diverse data types, as exemplified by the Array type (e.g., number[] or string[]). Syntaxlet myArra
2 min read
How to Declare Specific Type of Keys in an Object in TypeScript ?
In TypeScript, object definitions can include specific key-value types using index signatures. You can declare specific types of keys in an object by using different methods as listed below: Table of Content Using Mapped TypesUsing InterfaceUsing Inline Mapped Types with typeUsing Record Utility Typ
3 min read