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

Angular中如何从后端返回的多维数组提取指定字段生成新数组

Angular中提取JSON数据生成目标数组的解决方案

处理思路

从后端返回的响应中,遍历data数组里的每个对象,提取username中的id,并根据username里的字段存在情况选择fname或name,最终构造出目标数组。

代码实现

基础数据处理示例

// 模拟后端返回的响应对象
const backendResponse = {"data":[{"SRno":{"label":"newtest","label1":"10 VINS"},"attachment":{"value":null,"label":null},"username":{"id":2,"fname":"test1","lname":"test11"}},{"SRno":{"label":"newtest1","label":"10 VINS"},"attachment":{"value":null,"label":null},"username":{"id":3,"name":"test2","lname":"test22"}},{"SRno":{"label":"newtest2","label":"10 VINS"},"attachment":{"value":null,"label":null},"username":{"id":4,"name":"test3","lname":"test33"}},{"SRno":{"label":"newtest3","label":"10 VINS"},"attachment":{"value":null,"label":null},"username":{"id":5,"name":"test4","lname":"test44"}}],"result":null};

// 生成目标数组
const newArray = backendResponse.data.map(item => {
  const userInfo = item.username;
  return {
    id: userInfo.id,
    // 优先取fname,不存在则取name
    ...(userInfo.fname ? { fname: userInfo.fname } : { name: userInfo.name })
  };
});

console.log(newArray);
// 输出结果:[{"id":2,"fname":"test1"},{"id":3,"name":"test2"},{"id":4,"name":"test3"},{"id":5,"name":"test4"}]

Angular组件中实际请求处理示例

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-user-extractor',
  templateUrl: './user-extractor.component.html',
  styleUrls: ['./user-extractor.component.css']
})
export class UserExtractorComponent implements OnInit {
  targetArray: Array<{id: number, fname?: string, name?: string}> = [];

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    // 替换为你的后端接口地址
    this.http.get('/api/your-endpoint').subscribe((response: any) => {
      this.targetArray = response.data.map((item: any) => {
        const user = item.username;
        return {
          id: user.id,
          ...(user.fname ? { fname: user.fname } : { name: user.name })
        };
      });
    });
  }
}

可选优化:添加类型定义

为了代码更严谨,可定义对应接口约束数据类型:

// 定义用户信息类型
interface TargetUser {
  id: number;
  fname?: string;
  name?: string;
}

// 定义后端响应结构类型
interface BackendDataItem {
  SRno: { label: string; label1?: string };
  attachment: { value: null; label: null };
  username: TargetUser & { lname: string };
}

interface BackendResponse {
  data: BackendDataItem[];
  result: null;
}

使用时将请求响应指定为BackendResponse类型即可:

this.http.get<BackendResponse>('/api/your-endpoint').subscribe(response => {
  this.targetArray = response.data.map(item => {
    const user = item.username;
    return {
      id: user.id,
      ...(user.fname ? { fname: user.fname } : { name: user.name })
    };
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 08:35:40