Home > Mobile >  Access nested object properties in json object
Access nested object properties in json object

Time:04-14

how can I loop through the following object in Angular using *ngFor(suppousing there are many objects)? 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"  
    }
  },         
}

CodePudding user response:

that property is correct and you have to access it like this:

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

CodePudding user response:

you need to declare and access object.keys to use it in template

app.component.ts

objectKeys = Object.keys;

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

app.component.html

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

reference: Object.keys()

CodePudding user response:

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;
  }
}
  • Related