Eliminate items from an array using TypeScript

What is the procedure for removing an object from an array in typescript?

"revenues":[
{
        "drug_id":"20",
        "quantity":10
},
{
        "drug_id":"30",
        "quantity":1    
}]

I am looking to delete the drug_id from all objects. Can you provide guidance on how to accomplish this? Thank You!

Answer №1

Here is a solution you could consider:

this.revenues = this.revenues.map(r => ({quantity: r.quantity}));

If you are looking for a more versatile approach, you can try the following method:

removePropertiesFromRevenues(...props: string[]) {
  this.revenues = this.revenues.map(r => {
    const obj = {};
    for (let prop in r) { if (!props.includes(prop)) { obj[prop] = r[prop]; } }
    return obj;
  });
}

Answer №2

To implement the Array.prototype.map method, follow this pattern:

results = input.map(item => ({property: item.property}));

By using Array.prototype.map, each element in the input array can be customized before being returned.

The map() function generates a new array by applying a specified operation to each element within the original array.

If, for instance, you wish to modify each property and create additional fields, consider the following approach:

results = input.map(item => ({property: item.property, doubledProperty: item.property * 2}));

Answer №3

everything seems to be functioning properly

for (let rev of revenues) {
  delete rev.drug_id;
}

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

Angular - Creating validations for numeric input fields within reactive forms to ensure values fall within a designated range

One issue I am facing in my Angular form is with a numeric input field. The requirement is to set the minimum value as 3 and the maximum value as 10. However, upon loading the form, the default value should be 0. Users are expected to enter values ranging ...

Is it permissible to employ binding within the <script> element on an html page?

Is it feasible to apply binding within script tags on an HTML page? For instance: <script src="{{SOME_VARIABLE}}"></script> Would this be a viable option? ...

Retrieve host and path details using Angular Universal

Is there a way to retrieve hostname and pathname information in Angular universal? On the client side app, access to this information is available through the window object. I'm looking for a solution to get this information on the server side as we ...

Tips on accessing the formControl element within a formBuilder array

Is there a way to retrieve the value from mat-autocomplete when using formControlName? It seems that mat-autocomplete doesn't work in this scenario. <mat-form-field> <mat-label>...</mat-label> <input type="text ...

What is the best way to create a type that can accept either a string or a

I'm working with a map function and the parameter type is an array of strings or numbers. I've defined it as: (param: (string | number)[]) => ... However, I want to simplify it to: (param: StringOrNumber)[]) => ... Having to repeat the ...

Delivering emails with attachments using Angular 8

I've been attempting to send an email with an attachment using Angular 8. Here's the code I've tried: <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="51283e2423343c30383d11343c30383d7f323e3c"&g ...

Angular FormArray does not remove item properly upon using removeAt

I am facing an issue with a FormArray that contains a list of items. I am trying to add a button to remove an item from the FormArray. However, when I click the button, it clears the form value but does not remove the item from the front end. I'm not ...

Workers in Async.js queue failing to complete tasks

Creating a job queue to execute copy operations using robocopy is achieved with the following code snippet: interface copyProcessReturn { jobId: number, code: number, description: string, params: string[], source: string, target: s ...

The HttpClient.post request is working properly, however the Rest API is unable to retrieve the data

I need help with saving information from my Angular application into a database. I am utilizing the HttpClient to send data via POST requests to the RestAPI. The request is being sent, however, the API does not receive the data and instead returns a respon ...

There seems to be an incorrect number of arguments in the `getDownloadURL` function for Firebase Storage. It was expected to receive

I need assistance with retrieving the download URL of an image immediately after uploading it. Here is the code I am using: let image : string = 'promo_' + this.username + '_' + new Date() + '.png', storageRe ...

What is the best way to retrieve the parameter of ng2-file-upload using endback?

I am attempting to retrieve a parameter using PHP in order to save it into a folder. However, my code is not working as expected. Here is the code snippet: Using the Ionic framework this.uploader.onBeforeUploadItem = (item: any) => { this.uploader ...

Hide Angular Material menu when interacting with custom backdrop

One issue I am facing is with the menu on my website that creates a backdrop covering the entire site. While the menu can be closed by clicking anywhere outside of it, this functionality works well. The problem arises when users access the site on mobile ...

Using Typescript, creating an asynchronous function that utilizes a nested forEach loop to call another asynchronous function

Recently, I encountered an issue with an asynchronous function. I have two async functions that I am using. The problem arises because the return value is a promise, and I cannot await it inside the foreach loops. I attempted to make both foreach async, b ...

Jest ran into a surprising token related to NUXT typescript

After spending two days searching and trying various solutions without success, I am reaching out for help. Can anyone provide a clue? Below are the configuration files I am using. Any assistance would be greatly appreciated. jest.config.js .babelrc .babe ...

Could it be possible for TypeScript inference to directly infer the value and omit the key in the process?

class A { state: B } class B { something: C } class C { a: string; b: boolean; } type MagicType = ... const c: MagicType<A> c.state.a = "123" c.state.b = true; Is it possible to achieve the mentioned functionality without altering the exi ...

Interactive Modal Featuring Image Slider - Capture Names and Sequential Numbers

I successfully created a modal with an image slider using the bootstrap ngb-carousel. Is there a way to dynamically display the current image's name in the modal header and the numbering of images in the modal footer? For example, I want the modal h ...

What is the best approach for retrieving an image efficiently with Angular HttpClient?

My backend currently sends back an image in response. When I access this backend through a browser, the image is displayed without any issues. The response type being received is 'image/jpeg'. Now, I am exploring different methods to fetch this ...

Error: The script "build:universal" is required but not found in the

I encountered errors while attempting to run my Angular application on the server side: npm ERR! missing script: build:universal npm ERR! A complete log of this run can be found in: npm ERR! /home/training/.npm/_logs/2018-10-03T11_50_40_593Z-debug.lo ...

Discovering the previously selected index in an Angular mat stepper can be achieved by following a

How can I disable certain buttons in step 2 of an angular mat stepper when the user navigates from step 4 to step 2? I am attempting to implement a condition where if the selectedIndex is 1 and the previously selected index was 3, then the buttons should ...

Ionic 5 page div within ion-contents element is experiencing scrolling issues on iPhone devices

My application features a div element containing an ion-slides component. The ion-slides component houses several ion-slide elements that slide horizontally. Here is the relevant code snippet: <ion-content [scrollEvents]="true"> <div ...