converting data rows to columns

i have bellow object array

var dataarray = [
                   {
                    "Country": "America",
                    "Total": 200,
                    "Month" : "Jan"
                   },
                    {
                    "Country": "America",
                    "Total": 100,
                    "Month" : "Feb"
                   },
                   {
                    "Country": "India",
                    "Total": 100,
                    "Month" : "Feb"
                   }
]

from there what im expecting is like bellow

var final_array [
                 {"Country" : "America",
                  "Jan": 200,
                  "Feb" : 100
                 },
                 {"Country" : "India",
                  "Jan": 0,
                  "Feb" : 100
                 }
                ]

for some country not all the month will be there. only the month with data will be retrieved but in the final result if the month not present in original array the value should 0. like the above same array

i tried something like bellow but not able continue further as I’m not able to implement it

 dataarray.forEach(entry => {
          let line = result.find(resultEntry => resultEntry.Country=== entry.Country);
          
          if (line) {
              result = result.filter(resultEntry => resultEntry.Country!== line.Country);
              result.push({ ...entry, ...line })
          } else {
              result.push(entry)
          }
          });

>Solution :

This code should produce the desired output as shown in your final_array example. It iterates through the dataarray, builds the new structure, and then ensures that all months are present with their respective values, filling in missing months with zeros.
javascript

var dataarray = [
  {
    "Country": "America",
    "Total": 200,
    "Month": "Jan"
  },
  {
    "Country": "America",
    "Total": 100,
    "Month": "Feb"
  },
  {
    "Country": "India",
    "Total": 100,
    "Month": "Feb"
  }
];

var result = [];

dataarray.forEach(entry => {
  let existingCountry = result.find(country => country.Country === entry.Country);
  
  if (existingCountry) {
    existingCountry[entry.Month] = entry.Total;
  } else {
    let newCountry = { "Country": entry.Country };
    newCountry[entry.Month] = entry.Total;
    result.push(newCountry);
  }
});

// Add missing months and set their values to 0
var allMonths = Array.from(new Set(dataarray.map(entry => entry.Month)));

result.forEach(country => {
  allMonths.forEach(month => {
    if (!country.hasOwnProperty(month)) {
      country[month] = 0;
    }
  });
});

console.log(result);

Leave a Reply