0

I am getting JSON response as below :

bills : [
             {
                id: '111',
                date: '22 Jan 2020',
                amount: -250.00
            },
            {
                id: '222',
                date: '08 Jan 2020',
                amount: 700.00
            },
            {
                id: '333',
                date: '08 Feb 2020',
                amount: -250.00
            },
            {
                id: '788-609098-129169487',
                date: '08 Feb 2020',
                amount: 120.00
            }
    ]

I want to have object with only date and amount with month-wise total of amount like :

{
    "Jan" :
    {
        "month" : "Jan",
        "amount"  : 450.00
    },
    "Feb" :
    {
        "month" : "Feb",
        "amount"  : -130.00
    }

}

any help would be appreciated.

3
  • Does this answer your question? How do I remove a property from a JavaScript object? Commented Apr 6, 2020 at 16:19
  • 1
    Why do you use the month twice? Once as a key, once as a value? Why not using an array like : ``` [ { "month" : "Jan", "amount" : 450.00 }, { "month" : "Feb", "amount" : -130.00 } ] ``` Commented Apr 6, 2020 at 16:20
  • @Shiladitya I did checked that one but we're also adding the amounts' not just deleting. Commented Apr 6, 2020 at 16:24

1 Answer 1

2

const bills =  [
    {
       id: '111',
       date: '22 Jan 2020',
       amount: -250.00
   },
   {
       id: '222',
       date: '08 Jan 2020',
       amount: 700.00
   },
   {
       id: '333',
       date: '08 Feb 2020',
       amount: -250.00
   },
   {
       id: '788-609098-129169487',
       date: '08 Feb 2020',
       amount: 120.00
   }
];

const output = bills.reduce((a, {date, amount}) => {
    const month = date.slice(3, 6);

    if(!a[month]) { 
        a[month] = {"month": month, amount} 
    } else { 
        a[month].amount += amount ;
    }
    return a;
}, {});

console.log(output);

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

4 Comments

Amount is wrong. The first value gets added twice. This should solve: if(!a[month]) { a[month] = {"month": month, amount} } else { a[month].amount += amount; }
@LearningEveryday - Thanks a lot.
@random Is it possible to return array of objects instead of object of objects ?
@Veey - Yes. Use Object.values() on the final result of reduce. i:e Object.values(output).

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.