3

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!

ochs.tobi
  • 3,214
  • 7
  • 31
  • 52
Bereket Gebremeskel
  • 359
  • 1
  • 3
  • 11

3 Answers3

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;
  });
}
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}));
Laiso
  • 2,630
  • 3
  • 16
  • 32
  • what this actually will do?would u explain that to me?thanks in advance! – Bereket Gebremeskel Mar 12 '18 at 12:25
  • 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}` – Laiso Mar 12 '18 at 12:27
  • 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? – Bereket Gebremeskel Mar 12 '18 at 12:34
  • 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 – Laiso Mar 12 '18 at 12:38
  • You're welcome, so don't forget to upvote and mark the correct solution for your question! – Laiso Mar 12 '18 at 12:44
1

this should work

revenues.forEach((object) => delete object.drug_id );
mxr7350
  • 1,438
  • 3
  • 21
  • 29
Tom
  • 118
  • 1
  • 12