skip to Main Content

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

    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

2

Answers


  1. To convert multiple array object rows to a single row grouped by a key, you can use the reduce method in JavaScript. Here’s an example of how you can achieve the desired result:

    var dataarray = [
      { Region: 'Asia', Total: '0.50' },
      { Region: 'America', Total: '1.50' },
      { Region: 'Middle East', Total: '1.50' }
    ];
    
    var convertarray = dataarray.reduce((acc, entry) => {
      acc[entry.Region] = entry.Total;
      return acc;
    }, {});
    
    console.log(convertarray);
    

    This will output:

    {
      'Asia': '0.50',
      'America': '1.50',
      'Middle East': '1.50'
    }
    

    In the code above, we use the reduce method to iterate over the dataarray and accumulate the desired result in the convertarray object. For each entry, we assign the Total value to the corresponding Region key in the convertarray object.

    This approach eliminates the need for additional loops and checks for existing countries. The reduce method simplifies the code and provides a more concise solution.

    I hope this helps! Let me know if you have any further questions.

    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search