Typescript - Push value of arrivalDate in array

Viewed 26

How to get json parsed from api answer ?

3 Answers
searchForReservation() {
  alert('hello');
  this.http.get('/api/searchForReservation')
    .subscribe((data) => {
      const reservationInfo = this.data.result.reservations.reservationInfo;
      this.list = reservationInfo.map(e => e.roomStay.arrivalDate);
    })
}

Here's a working example in vanilla JS. You would need to make some small adjustments for angular, like this.list = ... instead of let list = ...

Using Array#map, you can create a new array from the JSON object

data.reservations.reservationInfo.map(r => r.roomStay.arrivalDate)

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

// declare your list as an array at the top
// list: []

// below would start off as 'this.list'
let list = data.reservations.reservationInfo.map(r => r.roomStay.arrivalDate);

console.log(list);

Your for loop is just reassigning the value of this.list

I suggest reading up on Array methods

I would use a map method, e.g.

this.list = this.ddataIno.result.reservations.reservationInfo.map(i => i.roomStay.arrivaldate);
Related