i have bellow array object
var datasource = [
{"Region": "America",
"Total_Time_Spent": "10",
"YearMonth": "2023 - October",
"projectname":"Project 1"},
{"Region": "America",
"Total_Time_Spent": "20",
"YearMonth": "2023 - October",
"projectname":"Project 2"},
{"Region": "America",
"Total_Time_Spent": "30",
"YearMonth": "2023 - June",
"projectname":"Project 3"},
{"Region": "Asia",
"Total_Time_Spent": "30",
"YearMonth": "2023 - June",
"projectname":"Project 4"}
]
based on the above I’m trying to create bellow array format
var Finaldatasource = [
{"Region": "America",
"YearMonth": "2023 - October",
"Project 1": "10",
"Project 2": "20",
"Project 3": "0",
"Project 4": "0"},
{"Region": "Asia",
"YearMonth": "2023 - October",
"Project 1": "0",
"Project 2": "0",
"Project 3": "0",
"Project 4": "0"}
{"Region": "America",
"YearMonth": "2023 - June",
"Project 1": "0",
"Project 2": "0",
"Project 3": "30",
"Project 4": "0"},
{"Region": "Asia",
"YearMonth": "2023 - June",
"Project 1": "0",
"Project 2": "0",
"Project 3": "0",
"Project 4": "30"}
]
means first two columns become Region and YearMonth followed by Project names as columns and value will be the hours spent
i have wrote bellow code and im able to get Region and followed by Project names as columns and value will be the hours spent. but how can also include YearMonth column
var Finaldatasource = [];
datasource.forEach(entry => {
let existingRegion = result.find(Region => Region.Region === entry.Region);
if (existingRegion) {
existingRegion[entry.projectname] = entry.Total_Time_Spent;
} else {
let newRegion = { "Region": entry.Region };
newRegion[entry.projectname] = entry.Total_Time_Spent;
result.push(newRegion);
}
});
// Add missing months and set their values to 0
var allMonths = Array.from(new Set(dataarray.map(entry => entry.projectname)));
result.forEach(Region => {
allMonths.forEach(month => {
if (!Region.hasOwnProperty(month)) {
Region[month] = 0;
}
});
});
2
Answers
I’ve got what you are looking for.
If you use es6, it can be done simply.
Here is a function
process()
that will compile your data into the desired format: