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

Angular中如何按规则重新整理JSON数组结构?

解决Angular中数组转换为指定分组JSON对象的问题

首先,我来帮你搞定这个数组分组转换的问题,你之前的代码在类型声明和逻辑实现上都有一些小问题,我会一步步帮你修正并实现符合预期的功能。

问题分析

你遇到的核心问题有两个:

  1. 类型声明错误:TypeScript里并没有list这个类型,你误用了这个不存在的类型来定义Map;
  2. 逻辑实现偏差:错误访问了数组的values属性(数组本身没有这个属性),而且没有实现按id分组的核心逻辑。

修正后的完整代码

下面是可以实现你期望输出的Angular组件代码,我添加了清晰的类型定义和注释:

import { Component } from '@angular/core';

// 定义数组中每个人员的类型,提升代码类型安全性
interface Person {
  id: string;
  country: string;
  name: string;
}

// 定义最终输出结果的类型
type GroupedResult = { [key: string]: { [name: string]: Person } };

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  // 用Person类型约束数组,避免any类型
  arrayList: Person[] = [
    {"id":"100","country":"india","name":"ram"},
    {"id":"100","country":"india","name":"sita"},
    {"id":"100","country":"india","name":"lakshman"},
    {"id":"109","country":"usa","name":"jhon"},
    {"id":"109","country":"usa","name":"adam"},
    {"id":"110","country":"uk","name":"andy"}
  ];
  // 存储最终转换后的结果
  groupedResult: GroupedResult = {};

  constructor() {
    // 第一步:先按id分组,把相同id的人员集合到一起
    const idGroups = new Map<string, Person[]>();
    this.arrayList.forEach(person => {
      // 如果当前id还没有分组,初始化一个空数组
      if (!idGroups.has(person.id)) {
        idGroups.set(person.id, []);
      }
      // 将当前人员添加到对应id的分组中
      idGroups.get(person.id)?.push(person);
    });

    // 第二步:将id分组转换为你期望的数字键结构,内层用姓名作为键
    Array.from(idGroups.values()).forEach((group, index) => {
      // 生成1、2、3这样的数字字符串键
      const groupKey = (index + 1).toString();
      // 将当前分组的人员转换为以name为键的对象
      this.groupedResult[groupKey] = group.reduce((acc, person) => {
        acc[person.name] = person;
        return acc;
      }, {} as { [name: string]: Person });
    });

    // 打印结果,和你期望的expectedOutputJson结构完全一致
    console.log(this.groupedResult);
  }
}

代码解释

  1. 类型定义:

    • Person接口明确了数组中每个元素的结构,让TypeScript可以提供类型检查和代码提示;
    • GroupedResult类型定义了最终输出的结构,确保转换结果完全符合你的预期。
  2. 分组逻辑:

    • 先用Map<string, Person[]>按id对人员进行分组,把相同id的人员放到同一个数组里;
    • 再将Map的分组结果转换成数组,遍历的时候用index + 1生成你需要的数字序号键;
    • 最后用reduce方法把每个分组的人员转换为以name为键的对象,每个键对应原人员对象。

运行这段代码后,groupedResult的结构就和你期望的expectedOutputJson完全一致了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 12:22:52