简体   繁体   中英

How can I read and bind data from this JSON to a Select dropdown in Angular 2+

This is what my JSON looks like:

{
    "Stations": {
        "44": {
            "NAME": "Station 1",
            "BRANCH_CD": "3",
            "BRANCH": "Bay Branch"
        },
        "137": {
            "NAME": "Station 2",            
            "BRANCH_CD": "5",
            "BRANCH": "Beach Branch"        
        }
    }
}

I would like to know if its possible to extract the "NAME" and "BRANCH" values from each "Station" and bind them to separate Select inputs [dropdowns]

I am using Angular 4. Here is what I have:

 this.apiService.getStations().subscribe(data => {
      this.stationList = data.Stations;
     }, err => {
      this.errorFetchingStations = err;
      console.log("Error getting list of stations " + err);
    })

this.stationList gives me an object of this format in the console:

{44:{NAME: "Name of station", BRANCH: "Name of branch"}}
{137:{NAME: "Name of station", BRANCH: "Name of branch"}}

and so on.

If I try to bind the stationList to my select like this, I get an error

ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

    <select class="form-control">
        <option *ngFor="let station of stationList" [value]="station.NAME">{{station.NAME}}</option>
      </select>

You are having key value pair to the object instead ngFor expects an array so you should use the below code

 this.apiService.getStations().subscribe(data => {
      this.stationList = Object.values(data.Stations); // returns an array
     }, err => {
      this.errorFetchingStations = err;
      console.log("Error getting list of stations " + err);
    })

you should transform the stationList to array and you can use the Object.values(data.Stations), as the below.

this.apiService.getStations().subscribe(data => {
  var stations = data.Stations;
  this.stationList = Object.values(stations);
}, err => {
  this.errorFetchingStations = err;
  console.log("Error getting list of stations " + err);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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