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

时间:2019-11-25 19:43:21

标签: arrays json angular

我发出了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请求加载数组?

2 个答案:

答案 0 :(得分:1)

使用简单的点符号访问数据的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; 
        });
}

答案 1 :(得分: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;
        } );