【问题标题】:Access object values in array nested in JSON object访问嵌套在 JSON 对象中的数组中的对象值
【发布时间】:2022-02-10 15:43:18
【问题描述】:

我有一个 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;
  • There's no such thing as a "JSON Object"data 是一个对象,“问题”中不涉及 JSON。
  • this.unit = this.model.Units[0];并且 this.unit.key 返回你的值...

标签: arrays angular typescript angular5


【解决方案1】:

你应该使用

this.unit = this.model.Units[0].Key;

而不是

this.unit = this.model.Units.Key; 

因为Units.Key 未定义

【讨论】:

  • 我试过了,现在收到这个错误:“无法获取未定义或空引用的属性‘键’”
  • 您确定从您的服务接收到 json 吗?尝试 console.log(this.model) 来确认。
  • 我确信它会回来,因为我的日期属性能够绑定在我的视图上
  • 这是 100% 正确的...我愚蠢地以为我在 Key 上指定索引并使用 'this.model.Units[1].Key' 并返回 undefined 因为嗯...a第二个对象不存在-_-。谢谢!
  • 欢迎您。请接受答案,这样它也会对其他人有所帮助
【解决方案2】:

由于 Units 是一个 JSON 数组,并且该数组仅包含一个元素。 它应该由 Units[0] 访问。

Units[0] 现在是 JSON,现在需要 Key 属性。 有两种访问方式

  1. Units[0].Key
  2. 单位[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();

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    相关资源
    最近更新 更多