我將 Ionic 與 Angular 一起使用。我有一個 JSON API 回應,我想在物件中獲取物件的專案,在本例中是作者專案。
JSON API 回應
{
x{
**authors**:{
auth-sara-rts-2022:
Code: "rts"
Contact:{
email:"[email protected]"
phone:"0.."}
[[Prototype]]: Object
auth-sami-sgs-2022:
Code: "sgs"
Contact:{
email:"[email protected]"
phone:"0.."}
[[Prototype]]: Object
[[Prototype]]: Object
}
[[Prototype]]: Object},
y{
yy: "text"
[[Prototype]]: Object}
[[Prototype]]: Object}
}
下面是如何在 ts 檔案中呼叫 API
callAPI(body: any, header: any): Observable<any> {
return this.http.post(API_URL API_ENDPOINT,body,header);
}
postAPI(body:any,header) {
this.callAPI(body, header).subscribe(
(data) => { console.log(data.x.authors);
}
);
}
我得到了一個作者串列,我想訪問每個作者收藏中的專案(代碼和聯系方式)。
我嘗試了這段代碼,但它回傳了一個未定義的值。
console.log(data.x.authors[0]);
uj5u.com熱心網友回復:
您遇到的問題是您嘗試使用陣串列示法 ( data.x.authors[0]) 來訪問物件中的鍵/值對。為了將authorsObject 轉換為 Array,有多種方法。我會建議Object.entries,它回傳一個元組陣列,每個元組包含鍵后跟值:
const authors = Object.entries(data.x.authors);
console.log(authors[0]); // ['auth-sara-rts-2022', { Code: 'rts', ... }]
以下是 MDN 檔案Object.entries():
https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/473244.html
