Vadivel A
Vadivel A

Reputation: 51

Javascript - Restructure the array of objects

I currently have an array of objects that looks like this:

[{day:"Monday", Country:"America", cases:200},
{day:"Monday", Country:"India", cases:120},
{day:"Monday", Country:"Germany", cases:20},
{day:"Tuesday", Country:"America", cases:210},
{day:"Tuesday", Country:"India", cases:110},
{day:"Tuesday", Country:"Germany", cases:35},
{day:"Wednesday", Country:"America", cases:250},
{day:"Wednesday", Country:"India", cases:150},
{day:"Wednesday", Country:"Germany", cases:50}]

I'm trying to figure out the best way to restructure this data to look like this:

[{day:"Monday", "America":200, "India":120, "Germany":20},    
 {day:"Tuesday", "America":210, "India":110, "Germany":35},    
 {day:"Wednesday", "America":250, "India":150, "Germany":50}]

Can anyone provide some advice for this and any good resources for restructuring javascript objects?

Upvotes: 0

Views: 443

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30675

We can use Array.reduce to create a summary of cases by day, and then by country.

We start by creating a map of cases, keyed on day, then we use Object.values to turn this map into an array.

I would suggest whenever you wish to restructure Arrays in general, have a look at Array.map, Array.filter, and Array.reduce, these are all powerful methods for changing Array structure.

const arr = [{day:"Monday", Country:"America", cases:200}, {day:"Monday", Country:"India", cases:120}, {day:"Monday", Country:"Germany", cases:20}, {day:"Tuesday", Country:"America", cases:210}, {day:"Tuesday", Country:"India", cases:110}, {day:"Tuesday", Country:"Germany", cases:35}, {day:"Wednesday", Country:"America", cases:250}, {day:"Wednesday", Country:"India", cases:150}, {day:"Wednesday", Country:"Germany", cases:50}];

const result = Object.values(arr.reduce((acc, cur) => {
    // Create the summary for the day if it doesn't exist
    acc[cur.day] = acc[cur.day] || { day: cur.day};
    // Create the summary for the country if it doesn't exist and add the cases in cur
    acc[cur.day][cur.Country] = (acc[cur.day][cur.Country] || 0) + cur.cases;
    return acc;
}, {}))

console.log('Result:',result)

Upvotes: 1

Related Questions