How do we map and object and add certain values and then get the total, I wanted to map the object below and then and items from the object. Anyone has an idea ?
Object:
[
{
"description": "Current Term",
"monthlyRent": 29971.599999999995,
"monthsInPeriod": 41.7,
"rentInPeriod": null
},
{
"description": "Current Term - Rent Adjustment",
"monthlyRent": 31470.180000000004,
"monthsInPeriod": 47.96666666666667,
"rentInPeriod": 1509519.634
}
]
29971.599999999995 41.7 = 30,012
31470.180000000004 47.96666666666667 = 31,517
Result: should be
total = 30,012 31,517
CodePudding user response:
You can use map
and reduce
to get the desired result:
const data = [
{
"description": "Current Term",
"monthlyRent": 29971.599999999995,
"monthsInPeriod": 41.7,
"rentInPeriod": null
},
{
"description": "Current Term - Rent Adjustment",
"monthlyRent": 31470.180000000004,
"monthsInPeriod": 47.96666666666667,
"rentInPeriod": 1509519.634
}
];
const total = data
.map(item => item.monthlyRent * item.monthsInPeriod)
.reduce((currentValue, acc) => acc currentValue);
I don't actually understand why would you want to add the monthlyRent
and the monthsInPeriod
so I multiplied them instead (to get the amount of money that needs to be payed during the number of months). If you want to add them like in your question, just replace the map with item.monthlyRent item.monthsInPeriod
.
CodePudding user response:
The
map()
method creates a new array populated with the results of calling a provided function on every element in the calling array. Refer the sample here.The
reduce()
method executes a user-supplied “reducer” callback function on each element of the array, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. Refer the sample here.
By combining both you can come up with solution like this:
let arry = [
{
"description": "Current Term",
"monthlyRent": 29971.599999999995,
"monthsInPeriod": 41.7,
"rentInPeriod": null
},
{
"description": "Current Term - Rent Adjustment",
"monthlyRent": 31470.180000000004,
"monthsInPeriod": 47.96666666666667,
"rentInPeriod": 1509519.634
}
];
let total = arry
.map(obj=> obj.monthlyRent obj.monthsInPeriod)
.reduce((value, previousValue) => previousValue value);
Another solution is to use simple for each:
let total2:number=0;
for (let i = 0; i < this.arry.length; i ) {
let val = this.arry[i].monthlyRent this.arry[i].monthsInPeriod;
total2 = total2 val
}
Please find the attached StackBlitz here.