问题
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