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 Create an Object in TypeScript?
TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data.Creating Objects in TypescriptNow, let
4 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() methodSetti
3 min read
How to Remove Spaces from a String in TypeScript ?
TypeScript offers various inbuilt functions to remove spaces from a string. These functions can be used to remove spaces between characters or entire words. Below, we explore different approaches to remove spaces from a string in TypeScript.Table of ContentUsing split() and join() methodsUsing repla
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 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 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.How to remove
3 min read
How to Cast Object to Interface in TypeScript ?
In TypeScript, sometimes you need to cast an object into an interface to perform some tasks. There are many ways available in TypeScript that can be used to cast an object into an interface as listed below: Table of Content Using the angle bracket syntaxUsing the as keywordUsing the spread operatorU
3 min read
How to make Mongo schema from pure Typescript classes ?
TypeScript is an object-oriented programming language, and it is a superset of JavaScript and contains all of its elements. By using TSC (TypeScript Compiler), we can convert Typescript code (.ts file) to JavaScript (.js file). It is open-source and its code is easier to read and understand. MongoD
8 min read