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

如何按指定属性对对象数组进行分类分组?

按指定属性分组对象数组(适配Angular ApexChart场景)

核心需求:根据服务器动态返回的属性,将对象数组分组,把同组对象的非分组属性值合并为数组,用于渲染Apex柱状图。

基础实现方案(原生JS/TS)

利用数组的reduce方法完成分组逻辑,无需额外依赖,直接在Angular中使用:

示例代码

const originalData = [ 
  {name: 'Alex', classroom: "A", Age: 25}, 
  {name: 'Rose', classroom: "A", Age: 24}, 
  {name: 'Peter', classroom: "B", Age: 21}, 
  {name: 'Alex', classroom: "C", Age: 22}
];

// 动态指定分组属性(可从API响应中获取)
const groupByKey = 'classroom';

const groupedData = Object.values(originalData.reduce((acc, item) => {
  const key = item[groupByKey as keyof typeof item];
  // 初始化分组对象
  if (!acc[key]) {
    acc[key] = { [groupByKey]: key };
    // 为非分组属性初始化空数组
    Object.keys(item).forEach(prop => {
      if (prop !== groupByKey) acc[key][prop] = [];
    });
  }
  // 收集当前对象的属性值到对应数组
  Object.keys(item).forEach(prop => {
    if (prop !== groupByKey) acc[key][prop].push(item[prop]);
  });
  return acc;
}, {} as Record<string, any>));

console.log(groupedData);

执行后将得到期望输出:

[
  {classroom: "A", name: ["Alex", "Rose"], Age: [25, 24]},
  {classroom: "B", name: ["Peter"], Age: [21] },
  {classroom: "C", name: ["Alex"], Age: [22] },
]

封装为Angular工具函数

为了复用性,可将分组逻辑封装为工具函数:

// utils.ts
export function groupByProperty<T>(data: T[], groupKey: keyof T): Array<Record<string, any>> {
  return Object.values(data.reduce((acc, item) => {
    const key = item[groupKey];
    if (!acc[key]) {
      acc[key] = { [groupKey]: key };
      Object.keys(item).forEach(prop => {
        if (prop !== groupKey.toString()) acc[key][prop] = [];
      });
    }
    Object.keys(item).forEach(prop => {
      if (prop !== groupKey.toString()) acc[key][prop].push(item[prop]);
    });
    return acc;
  }, {} as Record<string, any>));
}

在Angular组件中调用

// chart.component.ts
import { Component, OnInit } from '@angular/core';
import { groupByProperty } from './utils';

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html'
})
export class ChartComponent implements OnInit {
  chartData: any[] = [];
  // 实际场景中可替换为API请求返回的数据
  originalData = [ 
    {name: 'Alex', classroom: "A", Age: 25}, 
    {name: 'Rose', classroom: "A", Age: 24}, 
    {name: 'Peter', classroom: "B", Age: 21}, 
    {name: 'Alex', classroom: "C", Age: 22}
  ];

  ngOnInit(): void {
    // 假设从API获取到的分组属性为'classroom'
    const dynamicGroupKey = 'classroom';
    this.chartData = groupByProperty(this.originalData, dynamicGroupKey);
    // 将chartData传入ApexChart配置,完成渲染
  }
}

复杂场景扩展

  • 多属性分组:将多个属性组合为复合key(如const key = ${item.classroom}-${item.grade}``),后续逻辑保持一致。
  • 嵌套属性分组:若分组属性为嵌套字段(如item.student.classroom),调整key的取值逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 04:05:30