0

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?

1 Answer 1

1

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)

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

2 Comments

Thank you so much and for the suggestion. I was struck with the map itself and did not have much hands-on with reduce(). Your solution snippet really inspired me to learn more.
Map, Filter and Reduce are very useful, not just in JavaScript but many other languages too. Of course there are other techniques for manipulating arrays / lists etc, but mastering these will be a very good idea for any developer. Good luck with your project!

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.