0

So I was working on the some column merging and filtering,but I am having trouble calculating 2 object keys (columns) from an array of objects and then mapping that result to an object key to a new array

Example:

var foodRevenue = [{
    "Month": "2011-01",
    "week1_Revenue": "100.00",
    "week2_Revenue": "300.51",
    "Week3_Reenue": "200.09",
    "Month1_TotalRevenue": "0"
}];

I want to calculate the sum of week1, week2, and week3 and the result to map on Month1_TotalRevenue. Then creating a new array that would filter Month and Month1_TotalRevenue to that array. Like so:

{"Month": "2011-01", "Month1_TotalRevenue": "600.60"}

Any suggestions would be appreciated

2
  • There are no arrays shown, only objects... It's not clear what you mean. Commented Mar 11, 2020 at 15:41
  • FYI, it's typically safer to perform currency arithmetic times 100 so addition of fractional currency doesn't incur floating point error. Commented Mar 11, 2020 at 15:46

3 Answers 3

3

You may destructure your object properties and sum up desired ones, using Array.prototype.reduce():

const  foodRevenue = {
      "Month": "2011-01",
      "week1_Revenue": "100.00",
      "week2_Revenue": "300.51",
      "Week3_Reenue": "200.09",
      "Month1_TotalRevenue": "0"
    },
    {Month, Month1_TotalRevenue, week1_Revenue,...revenue} = foodRevenue,
    result = {
      Month,
      week1_Revenue,
      Month1_TotalRevenue: 
        Object
          .values({...revenue,week1_Revenue})
          .reduce((s,r) => s+=+r, +Month1_TotalRevenue)
          .toFixed(2)
    }
    
console.log(result)

Sign up to request clarification or add additional context in comments.

8 Comments

if I wanted to include "week1_Revenue" to the new array, would I add it to the result?
I added"week1_Revenue to result, but when I did that, it does not include week1 calculations into the foodRevenue calculations for MOnth_Revenue
@MarkAAvila : you may check out example for week1_Revenue standing out
@MarkAAvila : another thing that should be noted, if Month1_TotalRevenue is not 0, weekly revenues will be added to its value, if that is not a desired behavior, simply replace +Month1_TotalRevenue inside reduce() body with 0
note that foodRevenue is already an Object since originally it was a string so I JSON.parse()
|
1

You can use the function Map along with the function reduce as follow

This approach uses an array with the keys in the desired output, that way it's more dynamic.

let foodRevenue = [{"Month": "2011-01",    "week1_Revenue": "100.00",    "week2_Revenue": "300.51",    "Week3_Reenue": "200.09",    "Month1_TotalRevenue": "0"}];
let inArray = ["Month", "week1_Revenue"];
let accumulator = "Month1_TotalRevenue";
let result = foodRevenue.map(revenue => {
  let obj = Object.entries(revenue).reduce((r, [k, v]) => {
    if (inArray.includes(k)) r = Object.assign(r, {[k]: revenue[k]});
    return Object.assign(r, {[accumulator]: +(r[accumulator] || (r[accumulator] = 0)) + +v})
  }, {});
  
  obj[accumulator] = obj[accumulator].toFixed(2);
  return obj;
});

console.log(result);

4 Comments

the toFixed(), would that also have the decimal to be in the nearest thousandths?
if I wanted to include the week1_Revenue to the array without messing up the calculation, would that be possible?
@MarkAAvila see the updated answer
How could I change the order. Swapping Month1 and week1 order?
1

@Yevgen-Gorbunkov's answer is more concise...

    var foodRevenue = [{
        "Month": "2011-01",
        "week1_Revenue": "100.00",
        "week2_Revenue": "300.51",
        "Week3_Revenue": "200.09",
        "Month1_TotalRevenue": "0"
    }];


 let yearlyRevenue = foodRevenue.map((foodRevenue) => {
    let costs = 0

    for(let [key, value] of Object.entries(foodRevenue)) {
      if(key.indexOf('_Revenue') > -1){ // check if the key has _Revenue suffix
        costs += +value // +value change string to number
      }
    }

    console.log(costs);
    
    const transformed = { 
        Month: foodRevenue.Month,
        Month1_TotalRevenue: costs
    }

    return transformed
});

console.log(yearlyRevenue)

8 Comments

What if I wanted to calculate week1 and week2 only. how would I change the if statement?
if I know for definite I need only 2 props and I am sure of it then Id just do const total = +foodRevenue.week1_Revenue + +foodRevenue.week2Revenue
so I would replace let const?
let and const are just keywords. nothing to do with the total. const transformed = { Month: foodRevenue.Month, Month1_TotalRevenue: +foodRevenue.week1_Revenue + +foodRevenue.week2Revenue }
On your if statement, it would calculate all the index that has _revenue. That's the part I am confused.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.