I'm using Ionic with Angular. I have a JSON API response and I want to get the items of an object inside an object, in this case, author items.
JSON API response
{
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}
}
Here is how to call the API in ts file
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);
}
);
}
I get a list of authors, and I'd like to access the items in each author's collection (code and contact).
I tried this code, but it returned an undefined value.
console.log(data.x.authors[0]);
CodePudding user response:
The issue you're having is that you are trying to use Array notation (data.x.authors[0]
) to access key/value pairs in an Object. In order to transform the authors
Object into an Array, there are multiple approaches. I would propose Object.entries
, which returns an Array of tuples, each tuple containing the key followed by the value:
const authors = Object.entries(data.x.authors);
console.log(authors[0]); // ['auth-sara-rts-2022', { Code: 'rts', ... }]
Here are the MDN docs for Object.entries()
:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries