Skip to content Skip to sidebar Skip to footer

Calculating 2 Object Keys/columns From Array Of Objects Javascript

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 ob

Solution 1:

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)

Solution 2:

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]});
    returnObject.assign(r, {[accumulator]: +(r[accumulator] || (r[accumulator] = 0)) + +v})
  }, {});
  
  obj[accumulator] = obj[accumulator].toFixed(2);
  return obj;
});

console.log(result);

Solution 3:

@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 = 0for(let [key, value] ofObject.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)

Post a Comment for "Calculating 2 Object Keys/columns From Array Of Objects Javascript"