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

Angular中如何从JSON数组嵌套结构获取指定属性值?

解决Angular中从JSON数组提取指定字段的问题

问题根源

  1. 你的接口响应是数组类型,直接访问p?.properties会报错,因为数组本身没有properties属性
  2. properties是嵌套数组,需要先定位到数组内的元素,再访问property字段
  3. 原代码中type字段提取错误,JSON结构里的字段是type而非name

修正后的代码示例

1. 提取所有事件的type字段

// 结果为 ["session_start"]
type$ = this.service.getData().pipe(
  map((response: any[]) => response.map(event => event.type))
);

2. 提取第一个事件的第一个property值(即目标结果"activity")

// 结果为 "activity"
props$ = this.service.getData().pipe(
  map((response: any[]) => response[0]?.properties[0]?.property)
);

3. 提取所有事件的所有property值(返回数组)

如果需要获取JSON中所有property字段的值:

// 结果为 ["activity"]
allProps$ = this.service.getData().pipe(
  map((response: any[]) => 
    response.flatMap(event => 
      event.properties.map(prop => prop.property)
    )
  )
);

类型优化(推荐)

为了避免any类型带来的类型不安全问题,可以定义对应接口:

// 定义嵌套结构的类型接口
interface PropertyItem {
  property: string;
  type: string;
}

interface EventData {
  type: string;
  properties: PropertyItem[];
}

// 使用类型约束后的代码
type$ = this.service.getData().pipe(
  map((response: EventData[]) => response.map(event => event.type))
);

props$ = this.service.getData().pipe(
  map((response: EventData[]) => response[0]?.properties[0]?.property)
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:06:27