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 redu
3 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? In JavaScript, objects store data in key-value pairs. Sometimes, it is necessary to remove a specific key and its associated value from an object to update, clean, or manipulate data dynamically. Methods to Remove a Key-Value Pair from an ObjectThere are several methods that can be used to remove a
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 ContentUsing t
4 min read
How to Deep Merge Two Objects in TypeScript ? Merging two objects in TypeScript is a common task, but when dealing with complex nested structures, a deep merge becomes necessary. A deep merge combines the properties of two or more objects, including nested objects, creating a new object with merged values. In this article, we will explore vario
4 min read