Removing a dynamic TypeScript object key was successful

In TypeScript, there is a straightforward method to clone an object:

const duplicate = {...original}

You can also clone and update properties like this:

const updatedDuplicate = {...original, property: 'value'}

For instance, consider the following code snippet:

const object = {
    'key1': 1,
    'key2': 2,
};
const keyToDelete = 'key1';
delete object[keyToDelete];

Is there a more elegant way to delete a property from an object, without resorting to the conventional delete object[keyToDelete] approach? (and obviously not using object[keyToDelete] = undefined)

Answer №1

If you're searching for a way to use computed property names and destructuring in JavaScript, this code snippet may help. Learn more here

const a = {
    'something': 1,
    'e': 2,
};

const c = 'something';

const { [c]: _, ...withoutC } = a;

In this example, the value of the property something (retrieved from the variable c) is assigned to the _ variable, while all other properties are stored in the withoutC variable. Defining c as a constant allows TypeScript to correctly infer the type of withoutC.

Answer №2

Instead of removing the property from a, you can utilize destructured assignment to create a new object without that property:

const {c, ...b} = a;

Once this is done, b will include all elements of a except for c.

If a is defined as a certain type like { c: string, d: string }, then the types of c and b will be automatically deduced as string and { d: string } respectively. However, using an Omit type, as suggested by @Nurbol Alpybayev, would be more efficient than manually specifying the types.

To avoid any naming conflicts with another variable, you can rename c using this syntax:

const {c: someOtherName, ...b} = a;

This method works well if you are aware of the property name during compilation. If the property name is not known beforehand, then TypeScript may not provide accurate assistances in determining the result type of the operation.

In such scenarios, it's better to define a as { [k: string]: number } so that delete a[c] would suffice, or you can consider using the following approach:

const exclude = <T>(map: { [k: string]: T }, omitted: string[]): { [k: string]: T } =>
  return Object.getOwnPropertyNames(a)
    .filter(k => omitted.indexOf(k) >= 0)
    .reduce((a, k) => (a[k] = map[k], a), {})
};
var b = exclude(a, ["c"]);

Answer №3

Of course! Achieving this can be done by utilizing the Omit method:

type Omission<T, K> = Extract<T, Exclude<keyof T, K>>

type RemoveFoo = Omission<{foo: 'abc', bar: 'def'}, 'foo'> // {bar: 'def'}

By the way, it just dawned on me that your question may have been directed towards extracting values rather than types. If so, you might want to explore JavaScript instead of TypeScript.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a new JSON by extracting a specific branch or node from an existing JSON data

I have a Nuki Smartlock and when I make two API calls to the Nuki Bridge, I receive JSON responses. I want to apply the same logic to both responses: When requesting for current states, the JSON looks like this: [{ "deviceType": 0, "nuk ...

Sending form data from React to Express involves creating a form in the React component,

Hello, I am new to React and trying to figure out how to send registration data from a form submission to my backend. I have attempted the traditional method of setting up the post method and route in the form, but it doesn't seem to be working for me ...

Postpone the processing of a message in the Service Bus Queue until a specific time using NodeJS

Despite trying multiple tutorials, I have been unable to achieve the desired result so far. Currently, my setup involves a nodejs app that sends messages to the Service Bus Queue and another nodejs app that continuously polls it. The goal is to schedule a ...

Ways to retrieve the data received from an axios.post request in the server-side code

Currently, I am working on a project that involves using React for the frontend and Spring Boot for the backend. However, I am facing an issue with retrieving data that I have sent using Axios from the frontend to the backend. The code snippet below show ...

What is the best way to create a continuous loop of images on a never-ending

Many discussions cover similar topics, but I have not yet found a solution to my specific question. Currently, I am working on creating a model for a website and I am interested in incorporating an infinite rotating gallery with a limited number of images ...

Compiler error occurs when trying to pass props through a higher-order component via injection

Recently, I have been experimenting with injecting props into a component using a higher order component (HOC). While following this insightful article, I came up with the following HOC: // WithWindowSize.tsx import React, {useEffect, useMemo, useState} fr ...

Ways to update the component's state externally

I'm new to Next.js (and React) and I'm attempting to update the state of a component from outside the component. Essentially, I am conditionally rendering HTML in the component and have a button inside the component that triggers a function to se ...

Exploring the functionality of Material-UI's TextField component through role-based testing with React

I currently have some components that contain mui TextFields, and there are two specific scenarios for these components: One TextField is meant for LicenseCode and does not require a label. Additionally, there are several TextFields generated using t ...

Placing a div with position:absolute inside another div with position:absolute and turning them into position:fixed

HTML <div class="box1"></div> <div class="box2"> <div class="box3"></div> </div> CSS Properties of box1, box2 and box3 are: box1 { position: absolute; z-index: 100; background-color: rgba(39, 39, 39, 0.3) ...

Guide to retrieving environment variables within React/Node.js applications running in Kubernetes pods

While setting environment variables in Kubernetes pods, I encountered an issue when trying to access them in either Node.js or React front-end code using process.env.TEST (where TEST is present in the environment as secrets), as it always returned undefine ...

"Learn the trick of converting a stream into an array seamlessly with RxJs.toArray function without the need to finish the

In order to allow users to filter data by passing IDs, I have created a subject that can send an array of GUIDs: selectedVacancies: Subject<string[]> = new Subject(); selectedVacancies.next(['a00652cd-c11e-465f-ac09-aa4d3ab056c9', ...

Tips for transforming the input date value from Mui Datepicker

import * as React from "react"; import moment from "moment"; import TextField from "@mui/material/TextField"; import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs"; import { LocalizationProvider } from &quo ...

Tips for transforming a JSON response into an array with JavaScript

I received a JSON response from an API: [ { "obj_Id": 66, "obj_Nombre": "mnu_mantenimiento_de_unidades", "obj_Descripcion": "Menu de acceso a Mantenimiento de Unidades" }, { "obj_Id": 67, "ob ...

Is there a way to locate a null string within this data arrangement?

I am looking to create functionality where, when a button is clicked, the application checks the state and takes different actions based on the result. Specifically, I want to ensure that there are no empty "value" fields, and if there are, redirect to ano ...

Employ the find() function to ascertain the result of a condition

I'm struggling to grasp how to utilize the find() method in a conditional statement. In simple terms, I want the conditional to evaluate as true if the value of item.label is equal to the value of e.target.value. if (this.props.Items.find(item => ...

Searching for a streamlined approach to retrieve a segment of a string

I'm currently working with JavaScript and TypeScript. Within my code, I encountered a scenario where I have a string that might contain certain tags indicating importance or urgency. Here are a couple of examples: A: "Remind me to go to the store to ...

Include an additional icon without replacing the existing one on the mouse cursor

I am looking for a way to enhance the user experience by adding an icon that appears when hovering over an HTML element, serving as a subtle hint that the user can right-click. Instead of replacing the default cursor, which varies across platforms and doe ...

Problem with finding Rails controller file in .coffee extension

I recently started learning Rails and came across a file called welcome.js.coffee in the assets javascripts directory. # Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in applica ...

Retrieve data in JSON format from an external source file

I've been attempting to retrieve JSON content from an external file named list.json, but unfortunately all of my efforts have been unsuccessful. I've created a prototype of my code on Jsfiddle (http://jsfiddle.net/ctmvcyy1/). I believe that the ...

There was an issue: Control with the name 'name' could not be located

Whenever I submit the form and try to go back, an error pops up saying "ERROR Error: Cannot find control with the name: 'name'". I'm not sure what I might be missing. Do I need to include additional checks? Below is my HTML file: <div ...