Veey
Veey

Reputation: 246

Create object from JSON response remove unwanted key-values

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.

Upvotes: 0

Views: 96

Answers (1)

random
random

Reputation: 7891

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

Upvotes: 2

Related Questions