2

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!

2
  • 1
    The arguments of the .reduce() callback are (previousValue, currentValue) => { ... } ). You've swapped them in your script, hence data will be productMap/{} Commented Dec 10, 2021 at 17:15
  • I totally overlooked this, thank you! Commented Dec 10, 2021 at 17:20

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@Milos, check this out !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.