I have following array of hashes and want to convert it into an array like the one at the bottom of the post.
var responseData = [
{deviceType: "Smartphone", deviceCount: 14},
{deviceType: "Tablet", deviceCount: 11},
{deviceType: "Notebook", deviceCount: 3},
{deviceType: "Desktop", deviceCount: 2},
{deviceType: "Smartphone", deviceCount: 1},
{deviceType: "Tablet", deviceCount: 10},
{deviceType: "Notebook", deviceCount: 30},
{deviceType: "Desktop", deviceCount: 20}
];
function dataMapper(responseData){
let series = [];
if(responseData && responseData.length){
responseData.forEach(function(resource){
existingElement = series.filter(function (item) {
return item.deviceType === resource.deviceType;
});
if (existingElement) {
deviceCount = existingElement[0].deviceCount + resource.deviceCount;
existingElement[0].deviceCount = deviceCount
}else{
series[0].push({deviceType: resource.deviceType, y: resource.deviceCount});
}
});
}
return series
}
console.log(dataMapper(responseData))
I want to convert this into:
var expectedResult = [
{deviceType: "Smartphone", deviceCount: 15},
{deviceType: "Tablet", deviceCount: 21},
{deviceType: "Notebook", deviceCount: 33},
{deviceType: "Desktop", deviceCount: 22}
];