skip to Main Content

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

2

Answers


  1. 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);
    
    Login or Signup to reply.
  2. Create an object with all the available month names set as the as key name, and its value set to zero.

    Create another object with the country names as keys with their initial value an object spreading out the months object to get their initial values. Then add the the months and totals to the object using the Country value.

    const data=[{Country:"America",Total:200,Month:"Jan"},{Country:"America",Total:100,Month:"Feb"},{Country:"India",Total:100,Month:"Feb"}];
    
    const months = {};
    
    // Create a new object with the month names that
    // appear in the data, with the name of the month
    // as the and its value set to zero 
    for (const { Month} of data) {
      months[Month] = 0;
    }
    
    // Initialise an empty object
    const out = {};
    
    // Iterate over the data - destructure out
    // the keys/values from each object, create a new
    // object with a Country key if it doesn't exist
    // and spread out the months object into it. Assign 
    // the total to the month
    for (const obj of data) {
      const { Country, Month, Total } = obj;
      out[Country] ??= { Country, ...months };
      out[Country][Month] = Total;
    }
    
    // Finally create an array of objects
    // using Object.values
    console.log(Object.values(out));

    Additional documentation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search