简体   繁体   English

如何在 JSON API 响应中获取 object 的 object?

[英]How to get object of object in JSON API response?

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.我将 Ionic 与 Angular 一起使用。我有一个 JSON API 响应,我想在 object 中获取 object 的项目,在本例中为作者项目。

JSON API response JSON API 回复

   {
    x{
     **authors**:{
      auth-sara-rts-2022: 
           Code: "rts"
           Contact:{
              email:"xx@gmail.com"
              phone:"0.."}
           [[Prototype]]: Object
      auth-sami-sgs-2022: 
           Code: "sgs"
           Contact:{
              email:"xx@gmail.com"
              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下面是在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);

        } 
    );
  }

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]);

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.您遇到的问题是您正在尝试使用数组表示法 ( data.x.authors[0] ) 访问 Object 中的键/值对。为了将authors Object 转换为数组,有多种方法. I would propose Object.entries , which returns an Array of tuples, each tuple containing the key followed by the value:我会建议Object.entries ,它返回一个元组数组,每个元组包含键和值:

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以下是Object.entries()的 MDN 文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM