Search code examples
javascriptarraysnode8.4

How do I arrange a javascript array of objects from one format to another


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

I want to turn this array of objects:

[{
    client: '[email protected]',
    amount: 0,
    date: '2018-12'
},
{
    client: '[email protected]',
    amount: '30',
    date: '2018-11'
}, {
    client: '[email protected]',
    amount: '5',
    date: '2018-10'
}]

Into this:

[{
    client: '[email protected]',
    '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.


Solution

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

    const data = [{
        client: '[email protected]',
        amount: 0,
        date: '2018-12'
    },
    {
        client: '[email protected]',
        amount: '30',
        date: '2018-11'
    }, {
        client: '[email protected]',
        amount: '5',
        date: '2018-10'
    }]
    
    const result = data.reduce((memo, {client, date, amount}) => {
      memo.client = client;
      memo[date] = amount;
      return memo;
    }, {});
    
    console.log(result)