Как получить первый объект внутри объекта в angular 8 - PullRequest
0 голосов
/ 16 марта 2020

У меня есть json, мне нужно просто получить первый объект, в данном случае {"test": {"id": 1, "name": "cat"}} из данного объекта. Здесь объект выглядит следующим образом: {"3": {"test": {"id": 1, "name": "cat"}}, "4": {"test": {"id": 2, " название ":" собака "}}}. всегда может начинаться не с «3», а с «0». Вот код ниже

app.component. html

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  data:any;
   ngOnInit() {
  this.data = { "3": {"test": {"id":1, "name":"cat"}},
  "4": {"test": {"id":2, "name":"dog"}}};
  console.log(this.data);
}
}

Ответы [ 2 ]

0 голосов
/ 16 марта 2020
Html File
    <div *ngFor="let name of values">
    <hello name="{{ name }}"></hello>
    </div>

    TS File:
    export class AppComponent  {
      name = 'Angular';
      data: any;
    values:any=[];
      ngOnInit() {
        this.data = { 
          "3": {
            "test": {
              "id":1, 
              "name":"cat"
            }
          },
          "4": {
            "test": {
              "id":2, 
              "name":"dog"
            }
          }
        };

          this.values = Object.keys(this.data).map(key => this.data[key].test.name);

      }
    }
0 голосов
/ 16 марта 2020

Используйте Object.values ​​

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
data: any;
ngOnInit() {
    this.data = { '3': { test: { id: 1, name: 'cat' } }, '4': { test: { id: 2, name: 'dog' } } };
    console.log(this.data);
    const firstValue = Object.values(this.data)[0];
    console.log(firstValue);
   } 
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...