如何读取对象并将其存储到数组中

问题描述 投票:-1回答:2

我发出了http请求,然后返回了例如下面的json。我想在http请求时将汽车和鞋子对象读入单独的数组中。

json

{
 "id": 9, 
 "name": "Zlatan", 
 "cars": [
    {
     "type": "ford", 
     "year": "2019"
    },
    {
     "type": "audi", 
     "year": "2017"
    }
  ]
 "shoes": [
    {
     "brand": "adidas", 
     "status": "old"
    },
    {
     "brand": "timberland", 
     "status": "new"
    }
  ]
}

comp.ts

cars = [];
shoes = [];
//......

getZlatan() {
   return this.httpService.getInfo()
         .subscribe( data => {
                this.objZlatan = data;   //this part holds the json obj above
                this.cars ....//what to add here
                this.shoes ....// here too. 
            } );
}

或者有没有一种更清洁的方法来按http请求加载数组?

arrays json angular
2个回答
0
投票

只需使用.并键入名称即可访问carsshoes。让我举一个例子:

return this.httpService.getInfo()
     .subscribe( data => {
            this.objZlatan = data;   //this part holds the json obj above
            this.cars = data.cars;
            this.shoes =data.shoes;
        } );

0
投票

使用简单的点符号访问数据的carsshoes属性。最好用if(condition here)检查返回的数据是否不为null,然后执行逻辑。如果您有更多对象,并且想要将所有卡片和鞋子都放在一个阵列中,则必须循环通过。

getZlatan() {
    return this.httpService.getInfo()
        .subscribe(data => {
            this.objZlatan = data;
            this.cars = this.objZlatan.cars;
            this.shoes = this.objZlatan.shoes; 
        });
}
© www.soinside.com 2019 - 2024. All rights reserved.