如何将扁平JSON转换为分组合并JSON?
Merge Flat JSON into Grouped Structure by SchoolYear
Hey there! Let's tackle this task of converting a flat JSON array (split by SchoolYear and Type) into a merged structure where each unique SchoolYear has its own object with dedicated fields for each type's count and percentage.
Original Flat JSON
[ { "SchoolYear": 2017, "Type": "cat 1", "Count": 7236, "total": 43864, "Percentage": 16.50 }, { "SchoolYear": 2017, "Type": "cat 2", "Count": 36628, "total": 43864, "Percentage": 83.50 } ]
Target Merged JSON
[ { "SchoolYear": 2017, "cat 1 count": 7236, "cat 2 count": 36628, "total": 43864, "cat 1 Percentage": 16.50, "cat 2 Percentage": 83.50 } ]
Implementation (JavaScript)
We'll use Array.reduce() to group items by SchoolYear and dynamically build the merged object:
const flatData = [ { "SchoolYear": 2017, "Type": "cat 1", "Count": 7236, "total": 43864, "Percentage": 16.50 }, { "SchoolYear": 2017, "Type": "cat 2", "Count": 36628, "total": 43864, "Percentage": 83.50 } ]; const mergedData = Object.values(flatData.reduce((accumulator, currentItem) => { // Use SchoolYear as the grouping key const yearKey = currentItem.SchoolYear; // Initialize the group if it doesn't exist yet if (!accumulator[yearKey]) { accumulator[yearKey] = { SchoolYear: yearKey, total: currentItem.total // Assumes total is consistent per SchoolYear }; } // Add dedicated fields for count and percentage of the current Type accumulator[yearKey][`${currentItem.Type} count`] = currentItem.Count; accumulator[yearKey][`${currentItem.Type} Percentage`] = currentItem.Percentage; return accumulator; }, {})); console.log(mergedData);
How It Works
- Grouping with Reduce: We iterate over each item in the flat array, using
SchoolYearas the key to group items in an accumulator object. - Initialize Group: For each new
SchoolYear, we set up the base structure withSchoolYearandtotal. - Dynamic Field Creation: We take the
Typevalue and create custom field names (likecat 1 count) to store the correspondingCountandPercentagevalues. - Convert to Array: Finally,
Object.values()converts the grouped object back into an array of merged objects, matching your target structure.
Notes
- This assumes that
totalis the same for all items sharing the sameSchoolYear. If your data might have varying totals per year, you could adjust this logic (e.g., sum totals, or take the first occurrence). - The code works for any number of
Typevalues perSchoolYear—it will automatically add new fields as more types are encountered.
内容的提问来源于stack exchange,提问作者any
相关产品推荐
相关产品推荐

