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!
.reduce()callback are(previousValue, currentValue) => { ... } ). You've swapped them in your script, hencedatawill beproductMap/{}