【问题标题】:Typescript - JSON get value of specific Key in ArrayTypescript - JSON 获取数组中特定键的值
【发布时间】:2022-11-02 02:48:11
【问题描述】:

需要您的帮助才能访问数组中对象的特定值。 我想在对象 NumberR 中显示他们关键小时的每个值。 并在我的 Angular 前台显示上午 11 点和晚上 7 点。 API 返回的 Json:

{
    "reservations": {
        "reservationInfo": [
             {
                 "roomStay": {
                      "arrivalDate": "11am"
                 },
                 "WeatherR": {
                      "sound": "cloudy"
                 },
             },
             {
                  "roomStay": {
                      "arrivalDate": "7pm"
                   },
                  "WeatherR": {
                       "sound": "cloudy"
                   },
             }
        ]
    }
}

app.component.ts

  searchForReservation() {
    alert('hello');
    this.http.get('/api/searchForReservation').subscribe((res) => {
      this.ddataIno = res;
      console.log('MY DATA', this.ddataIno);
      this.unique = this.ddataIno.reservations.reservationInfo.map(
        (e) => e.roomStay.arrivalDate
      );
    });
  }

组件.html

<div class="test">
          <p>Arrival Date:</p><p>{{this.date}}</p>
</div>

【问题讨论】:

  • 您只想可视化小时数,对吗?

标签: json angular typescript


【解决方案1】:

您好,首先欢迎来到 StackOverflow 社区!

我可以建议您映射reservationInfo 并仅检索hours

searchForReservation() {
    alert('hello');
    this.http.get('/api/searchForReservation').subscribe((res) => {
      this.ddataIno = res;
      console.log('MY DATA', this.ddataIno);
      this.date = res.reservations.reservationInfo.map(
        (e) => e.roomStay.arrivalDate
      );
    });
  }

通过这种方式,您将小时数存储在 date 中(假设是一个数组)。之后,您可以通过ngFor 可视化您的数据,或者您可以创建不同的数据结构。

【讨论】:

  • JSON 属性每次都会更改,还是您有相同的?从您的更新中我看到NumberR 现在是roomStay,哪个是正确的?
  • 真的很抱歉让你感到困惑.. json 已更新,请查找该函数的最新版本,我刚刚更新了它。再次比你:)
  • 另外,我不明白这个错误:参数'e'隐含地具有'any'类型。这个变量 'e' 是什么?我好奇
  • 我发布的 JSON 是由我的浏览器发送的,它不是我项目中的 json 文件
  • @JulienFerrier e 具有隐式类型 any,因为您没有为该响应指定任何类型。您应该创建一个接口并使用它来指定响应类型。无论如何,我更新答案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多