Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert multiple Array object rows to one row, group by key

i have bellow array object

var dataarray = [{Region: 'Asia', Total: '0.50'},
                    {Region: 'America', Total: '1.50'},
                    {Region: 'Middle East', Total: '1.50'}]

i want to convert it like bellow

var convertarray = [{'Asia' : '0.50', 'America' : '1.50', 'Middle East' : '1.50'}]

i tried bellow way but it creates multiple rows even though groping by the region

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    var result = []; 

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

    var alldata = Array.from(new Set(dataarray.map(entry => entry.Region)));
  
    result.forEach(Region => {
    alldata.forEach(month => {
        if (!Region.hasOwnProperty(month)) {
            Region[month] = 0;
        }
    });
    });

any other way to archive desired result

>Solution :

It looks like all you’re doing is mapping each { Region : somekey, Total: value } object in your array to { somekey: value }, which you can do in a single step by taking advantage of JS’s bracket notation for property names:

const data = [
  { region: 'Asia', total: '0.50'},
  { region: 'America', total: '1.50'},
  { region: 'Middle East', total: '1.50'}
 ];
 
 const remapped = data.map(e => ({[e.region]: e.total}));
 
 console.log(remapped);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading