Reputation: 427
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>
Upvotes: 0
Views: 47
Reputation: 94
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);
})
Upvotes: 1
Reputation: 41581
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);
})
Upvotes: 1