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: '[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.

4
  • Can your array contain objects with various client email values or is it always the same one? Commented Dec 30, 2018 at 2:07
  • @nem035 same one Commented Dec 30, 2018 at 2:08
  • Then checkout the answer by ic3b3rg Commented Dec 30, 2018 at 2:09
  • Is it possible to have duplicate dates with different amounts? Commented Dec 30, 2018 at 2:39

3 Answers 3

4

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Do you mind explaining this code data.reduce((memo, {client, date, amount})
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?
1

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])

Comments

1

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.