4

how do i remove object from an array in typescript?

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

so i want to remove the drug_id from all objects. how do i achieve that? Thank You!

4

3 Answers 3

5

you could use that :

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

For a more generic way of doing this :

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;
  });
}
Sign up to request clarification or add additional context in comments.

2 Comments

this.revenues = this.revenues.map(r => ({quantity: r.quantity})); will it remove the quantity field? thanks
No, it will remove the id, like you asked
3

You can use the Array.prototype.map like this:

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

The Array.prototype.map will take each item of your revenues array and you can transform it before returning it.

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

So if you want for example double each quantity and add or rename some fields, you can do like below:

revenues = this.revenues.map(r => ({quantity: r.quantity, quantity2: r.quantity * 2}));

5 Comments

what this actually will do?would u explain that to me?thanks in advance!
The Array.prototype.map will transform your array to a new one depending on he given transformation rules returned by the callback. In this case, with the implicit return, our callback return a new object that holds only this field {quantity: r.quantity}
let's say i have "revenues":[ { "drug_id":"20", "quantity":10,, "price":10 }, { "drug_id":"30", "quantity":1 , "price":10 }] so i want to return only drug_id and quantity ,will urs option will do that?
So you need to write revenues = revenues.map(item => { drug_id: item.drug_id, quantity : item.quantity }). I will edit my answer to give you more explanation on how map works
You're welcome, so don't forget to upvote and mark the correct solution for your question!
1

this should work

revenues.forEach((object) => delete object.drug_id );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.