Reputation: 189
I have the following sample data.
ELEMENT_DATA: PeriodicElement[] = [
{ position: '06703851', weight: 10, billamount: 200, },
{ position: '06703852', weight: 20, billamount: 300, },
{ position: '06703853', weight: 30, billamount: 400, },
{ position: '06703854', weight: 40, billamount: 500, }
];
I get a column name dynamically and I need to perform the sum of that column. For instance, if the weight
column is passed, I should sum the weight
column and return the sum. I tried the following code and it's giving an error at t => selectedColumn
. Please help!!
caltotal(selectedColumn: string) {
this.total = this.ELEMENT_DATA.map(t => selectedColumn).reduce((acc, value) => acc + value, 0);
}
Upvotes: 0
Views: 100
Reputation: 51485
class PeriodicElement {
position!: string;
weight!: Number;
billamount!: Number;
[key: string]: any;
}
Access the property value with the index signature.
2.1. For the scenario with property is not a Number
type, you may check its type first and for my use case I default the value as 0 for property which is not a Number
type.
caltotal(selectedColumn: string) {
this.total = this.ELEMENT_DATA.map(t => t[selectedColumn])
.reduce((acc, value) => acc + (typeof value === 'number' ? value : 0), 0);
}
Upvotes: 1