访问嵌套在 JSON 对象中的数组中的对象值
Access object values in array nested in JSON object
我有一个 GET 请求发回一个结构如下的 JSON 对象:
{"ID":5176,
"DateFrom":"8/29/2018",
"DateTo":"8/29/2018",
"Units":[{"Key":"Value","Key2": "Value2"}]
}
我无法访问 Units[0] 值。我尝试了以下方法:
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();
}
我错过了什么?
你应该使用
this.unit = this.model.Units[0].Key;
而不是
this.unit = this.model.Units.Key;
因为 Units.Key
未定义
因为 Units 是一个 JSON 的数组,并且该数组只包含一个元素。
它应该由 Units[0].
访问
Units[0] 现在是 JSON,现在需要 Key 属性。
有两种访问方式
- 单位[0].Key
- 单位[0]['Key']
最终代码应该如下所示
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();
}
我有一个 GET 请求发回一个结构如下的 JSON 对象:
{"ID":5176,
"DateFrom":"8/29/2018",
"DateTo":"8/29/2018",
"Units":[{"Key":"Value","Key2": "Value2"}]
}
我无法访问 Units[0] 值。我尝试了以下方法:
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();
}
我错过了什么?
你应该使用
this.unit = this.model.Units[0].Key;
而不是
this.unit = this.model.Units.Key;
因为 Units.Key
未定义
因为 Units 是一个 JSON 的数组,并且该数组只包含一个元素。 它应该由 Units[0].
访问Units[0] 现在是 JSON,现在需要 Key 属性。 有两种访问方式
- 单位[0].Key
- 单位[0]['Key']
最终代码应该如下所示
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();
}