You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将扁平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

  1. Grouping with Reduce: We iterate over each item in the flat array, using SchoolYear as the key to group items in an accumulator object.
  2. Initialize Group: For each new SchoolYear, we set up the base structure with SchoolYear and total.
  3. Dynamic Field Creation: We take the Type value and create custom field names (like cat 1 count) to store the corresponding Count and Percentage values.
  4. 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 total is the same for all items sharing the same SchoolYear. 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 Type values per SchoolYear—it will automatically add new fields as more types are encountered.

内容的提问来源于stack exchange,提问作者any

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:22:40