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
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:This will output:
In the code above, we use the
reduce
method to iterate over thedataarray
and accumulate the desired result in theconvertarray
object. For each entry, we assign theTotal
value to the correspondingRegion
key in theconvertarray
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.
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: