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

56 views Asked by At

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.

3

There are 3 answers

2
ic3b3rg On BEST ANSWER

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)

0
connexo On

Using Array.prototype.reduce this would work:

const a = [{
    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 b = a.reduce((acc, {date, amount}) => {
  return { ...acc, [date]: amount }
}, { client: a[0].client })

console.log([b])

0
Mark On

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

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((obj, {client, date, amount}) => 
    Object.assign(obj, {client, [date]:amount}), {});

console.log([result])