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.

Veey
  • 216
  • 3
  • 13
  • Does this answer your question? [How do I remove a property from a JavaScript object?](https://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object) – Shiladitya Apr 06 '20 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 } ] ``` – C.Champagne Apr 06 '20 at 16:20
  • @Shiladitya I did checked that one but we're also adding the amounts' not just deleting. – Veey Apr 06 '20 at 16:24

1 Answers1

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);
random
  • 7,756
  • 3
  • 19
  • 25