[英]How to extract data from array instead of Object?
如何正確地從數組而不是 [Object] 中提取數據
api客戶端
export interface apiRequest {
locations: LocationOptions[];
}
interface FOLocations {
locationId: number;
}
interface LocationResult {
location: FOLocations[];
cityName: string;
}
export const locationCheck = async (
apiKey: string,
payload: apiRequest
): Promise<LocationResult[]> => {
let response = await axios.post<LocationResult[]>(
`api...`,
payload
);
return response.data;
運行代碼
const locationPayload : apiRequest = {
locations:[{ cityName: "London"},{cityName: "New York"},{cityName: "Paris"}],
};
const locationResponse = await locationCheck(apiKey,locationPayload);
const locationResponseRes = locationResponse;
console.log(locationResponseRes);
我需要獲取值 locationResponseRes.cityName。 實際 output:
[
{
location: { locationId: 1, address: [Object] },
deliveryOptions: [ [Object] ]
},
{
location: { locationId: 2,},
cityName: [ [Object] ]
}
]
{
"location": {
"locationId": 1,
cityName: [ [Object] ]
}
}
預期輸出(我在 Postman 中得到的)
[
{
"location": {
"locationId": 1,
"cityName: "London",
}
},
{
"location": {
"locationId": 2,
"cityName": "New York",
},
},
]
以及如何到達locationResponseRes.cityName
?
有幾種方法可用於控制台嵌套對象。
這樣做的最好方法,同時保留漂亮的打印,是使用
console.log(JSON.stringify(obj, null, 2))
其中 2 是用於縮進的空格數。
另一種選擇是使用
const util = require('util')
console.log(util.inspect(myObject, {showHidden: false, depth: null}))
// alternative shortcut
console.log(util.inspect(myObject, false, null, true /* enable colors */))
或者
require('util').inspect.defaultOptions.depth = null
console.log(obj)
但問題是 2 級之后的嵌套對象現在被展平了,這可能是復雜對象的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.