简体   繁体   English

访问 json 中嵌套的 object 属性 object

[英]Access nested object properties in json object

how can I loop through the following object in Angular using *ngFor(suppousing there are many objects)?如何使用 *ngFor(假设有很多对象)在 Angular 中循环遍历以下 object? I can't find how to access "type" property.我找不到如何访问“类型”属性。 Also I wonder whether "Animals Catalog" property is correct?另外我想知道“动物目录”属性是否正确? Thanks in advance.提前致谢。

{
  "name":"Richard",
  "lastname":"Garcia",
  "age":32,
  "pets":{
    "Animals Catalog":{
      "type":"cat",
      "gender":"male"  
    }
  },         
}

that property is correct and you have to access it like this:该属性是正确的,您必须像这样访问它:

<h1 *ngFor="let item of items">{{item.pets['Animals Catalog'].type}}</h1>

you need to declare and access object.keys to use it in template您需要声明并访问object.keys才能在模板中使用它

app.component.ts应用程序组件.ts

objectKeys = Object.keys;

obj = {
    name: 'Richard',
    lastname: 'Garcia',
    age: 32,
    pets: {
        'Animals Catalog': {
            type: 'cat',
            gender: 'male',
        },
    },
};

app.component.html app.component.html

<div *ngFor="let key of objectKeys(obj)">{{ key + ' : ' + obj[key] }}</div>

reference: Object.keys()参考: Object.keys()

Based on your code example:根据您的代码示例:

interface界面

export interface User {
  name: string;
  lastname: string;
  age: number;
  pets: Pet;
}

export interface Pet {
  [key: string]: PetDetail;
}

export interface PetDetail {
  type: string;
  gender: string;
}

component成分

<div *ngFor="let user of users">
 <p>{{ getValue(user) }}</p>
</div>
@Component(...)
export class Component {
  getValue(user: User): string {
     const keys = Object.keys(user);
    
     for (const key of keys) {
       const isPetObject = this.validateType(user[key]);
       
       if (!isPetObject) return user[key];
       
       const pets = user[key];
       const petKey = Object.keys(pets)[0]; // 'Animal Catalog'
       return pets[petKey]?.type; //cat
     }
  }

  private validateType(value: any): boolean {
    return typeof value !== string && typeof value !== number;
  }
}

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

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