Add the arrivalDate value to the existing array

Is there a way to store each arrivalDate from the API's JSON response into my array list, even though the array is currently empty?

Here is a snippet of the JSON returned by the API:

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

Below is a sample code snippet from component.ts:

searchForReservation() {
  alert('hello');
  this.http.get('/api/searchForReservation')
    .subscribe((data) => {
      this.ddataIno = data;
      this.ddataIno = this.ddataIno.result.reservations.reservationInfo;
      console.log('number of value', this.ddataIno.length);
      console.log('content', this.ddataIno);
      for (let i = 0; i <= this.ddataIno[i].length; i++) {
        this.list = this.ddataIno.roomStay.arrivalDate;
      }
      console.log('store array', this.list)

    })
}

Answer №1

findReservation() {
  alert('hey there!');
  this.http.get('/api/findReservation')
    .subscribe((data) => {
      const bookingDetails = this.data.result.reservations.bookingDetails;
      this.bookings = bookingDetails.map(e => e.roomBooking.arrivalDate);
    })
}

Answer №2

Check out this functional demo implemented in vanilla JS. Some minor tweaks may be required for angular, such as using this.collection = ... instead of let collection = ...

Utilizing the Array#map method allows you to generate a fresh array extracted from the JSON data

data.records.informationData.map(i => i.listing.description)

let data = {
  "records": {
    "informationData": [{
        "listing": {
          "description": "Luxurious villa"
        },
        "StatusR": {
          "type": "available"
        },
      },
      {
        "listing": {
          "description": "Cozy cabin"
        },
        "StatusR": {
          "type": "booked"
        },
      }
    ]
  }
}

// initialize your list as an empty array
// list: []

// or use 'this.collection' as the starting point
let collection = data.records.informationData.map(i => i.listing.description);

console.log(collection);

Answer №3

Your loop is simply updating the value of this.list

It might be beneficial to explore Array methods

An alternative approach could be using a map method, like so:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue encountered is when the data from the Angular form in the login.component.html file fails to be

I am struggling with a basic login form in my Angular project. Whenever I try to submit the form data to login.components.ts, it appears empty. Here is my login.component.html: <mat-spinner *ngIf="isLoading"></mat-spinner> & ...

Is there a universal method to transform the four array values into an array of objects using JavaScript?

Looking to insert data from four array values into an array of objects in JavaScript? // Necessary input columnHeaders=['deviceName','Expected','Actual','Lost'] machine=['machine 1','machine 2&apo ...

Utilizing React MUI Autocomplete to Save Selected Items

Exploring the realms of React and TypeScript, I find myself puzzled by a task at hand. It involves storing user-selected options from an Autocomplete component and subsequently sending these values to an external API. Is there a recommended approach for ac ...

Using promises in TypeScript index signature

Can you help me find the correct index signature for this particular class? class MyClass { [index: string]: Promise<void> | Promise<MyType>; // not working public async methodOne (): Promise<void> { ... } public async methodTwo () ...

What is the primary objective of the Angular Elements feature in Angular version 6?

One of the most intriguing features in Angular 6 is Angular Elements, which enables us to convert Angular Components into native Web Components. This means we can utilize them as web components in any framework, such as React or Vue. A critical question a ...

Next JS now includes the option to add the async attribute when generating a list of script files

We are currently working on a nextJs application and are looking to add asynchronous functionality to all existing script tags. Despite numerous attempts, we haven't been successful in achieving this. Can anyone provide some guidance or assistance? &l ...

How to Dynamically Load SVGs in Angular 10 Without Using IMG or OBJECT Elements

I have been exploring a more streamlined method for loading SVG files without relying on IMG or OBJECT tags, as it limits my ability to control fill colors through external CSS. While using inline SVG seems like the best option, managing numerous component ...

Extract the value from an array of objects

https://i.sstatic.net/fTShc.png Having some difficulty accessing the elements of an array. In order to assign a project name to a local variable projectName, I am seeking assistance with extracting the project name from the given JSON structure. Any hel ...

"Maximizing Space: A Guide to Setting BootStrap Navbar on the Right Side of the Page with Dropdown Width

Take a look at the image below. There is a navbar toggle button on the upper right corner of the page. When I expand it, the dropdown items occupy the entire width of the page, causing an issue where clicking anywhere within the red box triggers the dropdo ...

What is the best way to retrieve the index of the chosen option from a select element in Angular when

My Angular application includes a simple <select> element using Material design: <mat-form-field> <mat-label>Type</mat-label> <mat-select placeholder="Type" formControlName="type" name="type" id="name"> <mat-option ...

What's the most effective method for transferring data to different components?

How can I efficiently pass a user info object to all low-level components, even if they are grandchildren? Would using @input work or is there another method to achieve this? Here is the code for my root component: constructor(private _state: GlobalSta ...

"Error encountered: Route class unable to reach local function in TypeScript Express application" #codingissues

Experiencing an 'undefined' error for the 'loglogMePleasePlease' function in the code snippet below. Requesting assistance to resolve this issue. TypeError: Cannot read property 'logMePleasePlease' of undefined This error ...

Implementing a Dynamic Component within ngx-datatable's row-detail feature

I'm currently working on a project where I need to implement a reusable datatable using ngx-datatable. One of the requirements is to have dynamic components rendered inside the row details. The way it's set up is that the parent module passes a c ...

The issue encountered is: "Uncaught promise error: Provider for ActivatedRoute not found."

The dependencies listed in the package.json file are: "dependencies": { "@angular/cli": "1.0.0", "@angular/compiler-cli": "^4.0.0", "@angular/common": "^4.0.0", "@angular/compiler": "^4.0.0", "@angular/core": "^4.0.0", "@angular/forms": "^4.0.0", "@angula ...

What could be causing the transparency of my buttons when viewed on my device?

Recently, I customized the appearance of buttons in my App by adding colors. Surprisingly, everything looks perfect when I test it on a local server on my PC. However, once I deploy the App to my Android device, all the buttons become transparent. In my v ...

Learning the process of configuring neo4j connection details without relying on environment variables

Is there a way to specify the database connection in code using the Drivine neo4j driver without relying on environment variables? ...

How to count the array index in PHP and change an integer to a string

In my mysqli query, I retrieved an array that contains a list of tasks. My goal is to count the number of tasks in the array (i.e., the number of rows) and display this as a human-readable number on an icon badge. try { $db = new PDO("mysql:host= ...

How can you create an array in JavaScript?

Learning JavaScript has led me to discover the various methods for declaring arrays. var myArray = new Array() var myArray = new Array(3) var myArray = ["apples", "bananas", "oranges"] var myArray = [3] What sets them apart and which ways are typically ...

Exploring nullish coalescing with undefined values

My function is set up to make API calls: interface getEventsPropsShape { eventId?: string; accountId?: string; eventsStartAfter?: string; } const getEvents = async ({ eventId, accountId, eventsStartAfter, }: getEventsPropsSha ...

Contrast between sourcing a file from the current directory versus from the node_modules folder

Why does the typescript compiler accept importing from a JS file in the local directory but raises an error when importing from node_modules? Code: import { t2 } from "./t1.js" t2.hello(); import { mat4 } from "./node_modules/gl-matrix/esm ...