I have a payload coming back from an endpoint like this:
const charges = [
{
'id': 'someId',
'dates': ['2017-11-11', '2017-12-11'],
},
{
'id': 'anotherId',
'dates': ['2017-09-11', '2017-10-11'],
},
];
What would be the best way to attach id to each of the items in the dates array so that it results in this:
[
{ id: 'someId', date: '2017-11-11' },
{ id: 'someId', date: '2017-12-11' },
{ id: 'anotherId', date: '2017-09-11' },
{ id: 'anotherId', date: '2017-10-11' },
]
I've tried something like this:
let history = [];
charges.map(charge => (
charge.dates.map((date) => (
history.concat({
id: charge.payerCode,
date: date,
})
))
));
But history is not defined in the scope I'm using it in.
I know there is probably a better way to do this, but I just can't seem to wrap my head around it.
Any help would be greatly appreciated!
Thanks!
historycontain your desired output?mapisn't the right tool here as your output array won't possibly have the same number of elements than your input array.reduceis the tool to use, as proposed in the answers.