0

I feel like its a very simple answer but im having trouble figuring it out.

I want to turn this array of objects:

[{
    client: 'lalala@email.com',
    amount: 0,
    date: '2018-12'
},
{
    client: 'lalala@email.com',
    amount: '30',
    date: '2018-11'
}, {
    client: 'lalala@email.com',
    amount: '5',
    date: '2018-10'
}]

Into this:

[{
    client: 'lalala@email.com',
    '2018-12': 0,
    '2018-11': '30',
    '2018-10': '5'
}]

I've been trying with reduce() function but not getting anywhere close.

I appreciate you taking the time.

avatarZuko
  • 115
  • 5

3 Answers3

4

A reduce is the correct approach - here's how to do it:

const data = [{
    client: 'lalala@email.com',
    amount: 0,
    date: '2018-12'
},
{
    client: 'lalala@email.com',
    amount: '30',
    date: '2018-11'
}, {
    client: 'lalala@email.com',
    amount: '5',
    date: '2018-10'
}]

const result = data.reduce((memo, {client, date, amount}) => {
  memo.client = client;
  memo[date] = amount;
  return memo;
}, {});

console.log(result)
ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
  • Do you mind explaining this code `data.reduce((memo, {client, date, amount})` – brk Dec 30 '18 at 04:34
  • `memo` is the accumulator that is either the initialized value (`{}` in this case) or the returned value from the last iteration. `{client, date, amount}` are decomposed properties of each object in the iteration. make sense? – ic3b3rg Dec 30 '18 at 04:37
1

Using Array.prototype.reduce this would work:

const a = [{
    client: 'lalala@email.com',
    amount: 0,
    date: '2018-12'
}, {
    client: 'lalala@email.com',
    amount: '30',
    date: '2018-11'
}, {
    client: 'lalala@email.com',
    amount: '5',
    date: '2018-10'
}]

const b = a.reduce((acc, {date, amount}) => {
  return { ...acc, [date]: amount }
}, { client: a[0].client })

console.log([b])
connexo
  • 53,704
  • 14
  • 91
  • 128
1

Since the client will always be the same you can put Object.assign to good work in reduce():

const data = [{client: 'lalala@email.com',amount: 0,date: '2018-12'},{client: 'lalala@email.com',amount: '30',date: '2018-11'}, {client: 'lalala@email.com',amount: '5',date: '2018-10'}]

const result = data.reduce((obj, {client, date, amount}) => 
    Object.assign(obj, {client, [date]:amount}), {});

console.log([result])
Mark
  • 90,562
  • 7
  • 108
  • 148