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