Reputation: 414
I have a GET request that sends back a JSON object structured like this:
{"ID":5176,
"DateFrom":"8/29/2018",
"DateTo":"8/29/2018",
"Units":[{"Key":"Value","Key2": "Value2"}]
}
I cannot access Units[0] value. I have tried the following:
testFunction(){
this.service.getJSON(params)
.subscribe((data) => {
this.model = data;
this.dateFrom = this.model.DateFrom;
this.dateTo = this.model.DateTo;
this.unit = this.model.Units.Key;
console.log(this.unit); //undefined
});
}
}
ngOnInit() {
this.testFunction();
}
What am I missing?
Upvotes: 0
Views: 105
Reputation: 1
Since Units is an array of JSONs and the array contains only one element. It should be accessed by Units[0].
Units[0] is now a JSON, Key property is needed now. There are 2 ways to access it
The final code should look like
testFunction(){
this.service.getJSON(params)
.subscribe((data) => {
this.model = data;
this.dateFrom = this.model.DateFrom;
this.dateTo = this.model.DateTo;
//first method
//this.unit = this.model.Units[0].Key;
// second method
// this.unit = this.model.Units[0]['Key'];
console.log(this.unit); //undefined
});
}
}
ngOnInit() {
this.testFunction();
}
Upvotes: 0
Reputation: 1135
You should use
this.unit = this.model.Units[0].Key;
instead of
this.unit = this.model.Units.Key;
since Units.Key
is undefined
Upvotes: 1