如何从数组而非Object中正确提取数据,获取cityName字段值?
问题根源
- 你定义的TS接口和API实际返回结构不匹配:Postman返回的
cityName是嵌套在location对象内部的,不是和location平级的字段;且你定义的location是数组类型,但实际返回是单个对象。 locationResponseRes本身是数组,不能直接调用.cityName,需要先取数组内的对应元素,再访问嵌套层级的字段。- 控制台打印显示
[Object]是浏览器/Node对嵌套对象的默认折叠展示,不是数据丢失,用JSON.stringify打印即可看到完整内容。
修正方案
第一步:调整接口定义和API请求逻辑(和实际返回对齐)
export interface apiRequest { locations: LocationOptions[]; } // 补充FOLocations的cityName字段 interface FOLocations { locationId: number; cityName: string; // 有其他返回字段可自行补充类型 } // 修正LocationResult:location是单个对象而非数组 interface LocationResult { location: FOLocations; // 有deliveryOptions等额外返回字段可自行补充类型 } export const locationCheck = async ( apiKey: string, payload: apiRequest ): Promise<LocationResult[]> => { let response = await axios.post<LocationResult[]>( `api...`, payload ); return response.data; }
第二步:正确读取cityName值
const locationPayload : apiRequest = { locations:[{ cityName: "London"},{cityName: "New York"},{cityName: "Paris"}], }; const locationResponse = await locationCheck(apiKey,locationPayload); const locationResponseRes = locationResponse; // 可选:打印完整返回结构确认字段 console.log(JSON.stringify(locationResponseRes, null, 2)); // 场景1:提取所有返回结果的cityName列表 const allCityNames = locationResponseRes.map(item => item?.location?.cityName); console.log(allCityNames); // 输出 ['London', 'New York', ...] // 场景2:提取单条返回结果的cityName,比如第一条 const firstCityName = locationResponseRes[0]?.location?.cityName; console.log(firstCityName); // 输出 London
注意:代码中加入可选链
?.是为了避免数组为空、字段缺失时抛出异常,你可以根据实际业务场景调整校验逻辑。
内容的提问来源于stack exchange,提问作者PoolWorld
相关产品推荐
相关产品推荐

