如何从HTTP GET响应的JSON对象中提取属性与值至对应数组
提取API响应中的属性名与对应值到数组
嘿,这事儿不难,我给你捋清楚怎么搞!首先假设你的API返回的JSON结构大概是这样(结合你提到的ignition_state_off属性举例):
{ "ignition_state_off": 15, "door_unlocked": 8, "engine_idle": 22 }
接下来,在你注入服务的组件里,拿到响应后可以用Object.entries()方法轻松提取键值对,而且能严格保持原属性的顺序(ES6+的对象会保留字符串键的定义顺序,完全符合你的需求)。
具体实现代码(以Angular为例,其他框架逻辑通用)
import { Component, OnInit } from '@angular/core'; import { YourApiService } from './path-to-your-service'; @Component({ selector: 'app-target-component', templateUrl: './target-component.component.html' }) export class TargetComponent implements OnInit { // 定义要存储的两个数组 propertyNames: string[] = []; propertyValues: number[] = []; constructor(private apiService: YourApiService) { } ngOnInit(): void { // 调用服务获取API响应 this.apiService.fetchYourData().subscribe({ next: (apiResponse) => { // 遍历响应对象的键值对 Object.entries(apiResponse).forEach(([key, value]) => { // 把属性名存入string数组 this.propertyNames.push(key); // 确保值是number类型再存入数组,避免类型错误 if (typeof value === 'number') { this.propertyValues.push(value); } else { // 可选:处理非数字值的情况,比如转成数字或者打警告 console.warn(`注意:属性${key}的值不是数字,当前值为:${value}`); // 如果需要强制转数字,可以用:this.propertyValues.push(Number(value)); } }); // 验证结果(可以删掉,只是用来确认) console.log('属性名数组:', this.propertyNames); console.log('属性值数组:', this.propertyValues); }, error: (err) => { console.error('API请求出错啦:', err); } }); } }
额外的小技巧
如果你只需要提取特定规则的属性(比如只保留包含_state_的属性),可以在遍历前加个过滤:
Object.entries(apiResponse) .filter(([key]) => key.includes('_state_')) // 只保留带_state_的属性 .forEach(([key, value]) => { // 同上的处理逻辑 });
这样就能精准拿到你想要的那些属性啦!
内容的提问来源于stack exchange,提问作者ibrahim.bond
相关产品推荐
相关产品推荐

