从打字稿中的数组中删除对象
Remove objects from array in typescript
如何从打字稿中的数组中删除对象?
"revenues":[
{
"drug_id":"20",
"quantity":10
},
{
"drug_id":"30",
"quantity":1
}]
所以我想从所有对象中删除 drug_id。
我该如何实现?
谢谢!
你可以使用它:
this.revenues = this.revenues.map(r => ({quantity: r.quantity}));
更通用的方法:
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;
});
}
这应该有效
revenues.forEach((object) => delete object.drug_id );
您可以像这样使用 Array.prototype.map
:
revenues = this.revenues.map(r => ({quantity: r.quantity}));
Array.prototype.map
将获取您的 revenues
数组中的每一项,您可以在返回之前对其进行转换。
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
因此,例如,如果您想将每个数量加倍并添加或重命名一些字段,您可以像下面那样做:
revenues = this.revenues.map(r => ({quantity: r.quantity, quantity2: r.quantity * 2}));
如何从打字稿中的数组中删除对象?
"revenues":[
{
"drug_id":"20",
"quantity":10
},
{
"drug_id":"30",
"quantity":1
}]
所以我想从所有对象中删除 drug_id。 我该如何实现? 谢谢!
你可以使用它:
this.revenues = this.revenues.map(r => ({quantity: r.quantity}));
更通用的方法:
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;
});
}
这应该有效
revenues.forEach((object) => delete object.drug_id );
您可以像这样使用 Array.prototype.map
:
revenues = this.revenues.map(r => ({quantity: r.quantity}));
Array.prototype.map
将获取您的 revenues
数组中的每一项,您可以在返回之前对其进行转换。
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
因此,例如,如果您想将每个数量加倍并添加或重命名一些字段,您可以像下面那样做:
revenues = this.revenues.map(r => ({quantity: r.quantity, quantity2: r.quantity * 2}));