Angular中如何从JSON数组嵌套结构获取指定属性值?
解决Angular中从JSON数组提取指定字段的问题
问题根源
- 你的接口响应是数组类型,直接访问
p?.properties会报错,因为数组本身没有properties属性 properties是嵌套数组,需要先定位到数组内的元素,再访问property字段- 原代码中
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
相关产品推荐
相关产品推荐

