Remove objects from array in typescript

点点圈 提交于 2021-02-07 08:55:37

问题


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!


回答1:


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;
  });
}



回答2:


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}));



回答3:


this should work

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


来源:https://stackoverflow.com/questions/49234942/remove-objects-from-array-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!