How to assign object with properties to property of an object using reduce

Viewed 34

I have a data like this

const dataSet = [
   {
     'Transactions.productRef': 'SomeRef/123',
     'Transactions.itemCount': 25,
     'Transactions.revenue': 1000,
   },
   {
     'Transactions.productRef': 'SomeRef/124',
     'Transactions.itemCount': 35,
     'Transactions.revenue': 500,
   },
 ];

and I'm trying to assign an object with properties to the value of the 'Transactions.productRef' to have something like this

{
  'SomeRef/123': {
     productRef: 'SomeRef/123',
     soldTickets: 25,
     revenue: 1000,
   },
  'SomeRef/124': {
     productRef: 'SomeRef/124',
     soldTickets: 35,
     revenue: 500,
   }
 }

and then to create a new array with objects. I have tried something like this

const dataSet = [
  {
    'Transactions.productRef': 'SomeRef/123',
    'Transactions.itemCount': 25,
    'Transactions.revenue': 1000,
  }, {
    'Transactions.productRef': 'SomeRef/124',
    'Transactions.itemCount': 35,
    'Transactions.revenue': 500,
  },
];

const productMap = {};

dataSet.reduce((data, p) => {
    p[data['Transactions.productRef']] = p[data['Transactions.productRef']] 
       || {};
    p[data['Transactions.productRef']].soldTickets = 
       data['Transactions.itemCount'];
    p[data['Transactions.productRef']].revenue = 
       data['Transactions.revenue'];
    p[data['Transactions.productRef']].productRef = 
       data['Transactions.productRef'];
    return p;
 }, productMap);

 const newData = Object.values(productMap);
 console.log(newData);

but the console.log returns an empty array like the data was never assigned to the productMap object. What am I doing wrong? Thanks in advance!

1 Answers

Swap p and data in the reduce callback inputs like below.

Because first param is the previousValue and second param is the currentValue.

dataSet.reduce((p, data) => {
    p[data['Transactions.productRef']] = p[data['Transactions.productRef']] 
       || {};
    p[data['Transactions.productRef']].soldTickets = 
       data['Transactions.itemCount'];
    p[data['Transactions.productRef']].revenue = 
       data['Transactions.revenue'];
    p[data['Transactions.productRef']].productRef = 
       data['Transactions.productRef'];
    return p;
 }, productMap);
Related