How to retrieve a specific key value from a JSON array in Typescript

Struggling to access a specific value of an object within an array? I need your assistance. My goal is to showcase each value of the key "hours" in the object called NumberR, and then display 11am and 7pm on my Angular frontend. Here's the JSON returned by the API:

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

In app.component.ts file:

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

In component.html:

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

Answer №1

Greetings and a warm welcome to the StackOverflow community!

My recommendation would be to extract only the hours from the reservationInfo:

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
      );
    });
  }

This way, you can save the hours in the date variable (assuming it's an array). Subsequently, you can display your data using ngFor or create different data structures as needed.

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

Tips for extracting and mapping a sub array from the category response JSON using SWR with MongoDB in a Next.js (Node.js) environment

Can anyone assist me with reading and mapping arrays inside JSON? Using Hook (useSWR / useCategories): import useSWR from "swr" const fetcher = (...args) => fetch(...args).then(res => res.json()) function useCategories () { const { data, erro ...

Assess the equation twice using angular measurement

I am attempting to assess an expression that is originating from one component and being passed into another component. Here is the code snippet: Parent.component.ts parentData: any= { name: 'xyz', url: '/test?testid={{element["Te ...

Interactive mat-select within Angular material table

I have retrieved data from an endpoint and displaying it in a material table. However, I also have an additional column requestedStatus, which contains a mat-select with 2 options. I want the selected option to dynamically update the row by adding a new ke ...

Is it possible to view the object sent from AJAX to PHP in PHP using a debugger?

I'm facing an issue where I am making an AJAX call to a PHP file, sending a JSON object as a parameter from JavaScript. The PHP file is supposed to perform some logic with the object and return it using json_encode('whatever');. However, the ...

What is the best way to compare an array with comma-separated values in JavaScript?

I have a scenario where I have two arrays, one for categories and the other for products. Each product contains multiple categories as a comma-separated string. My goal is to match a specific category with each product's product_category value and the ...

Navigating back to the starting point

I'm experiencing an issue while trying to navigate using the Router.navigate method. Despite following all instructions meticulously, whenever I attempt to route via API, it reloads the root page. Within my RootComponent implementation, I am utilizin ...

Angular 2 validation issue not functioning as anticipated

Here is a validator function that I have: export const PasswordsEqualValidator = (): ValidatorFn => { return (group: FormGroup): Observable<{[key: string]: boolean}> => { const passwordCtrl: FormControl = <FormControl>group.contr ...

Having trouble locating a tag when converting an object to an array in Android using JSONArray

I am currently working on retrieving data from an API using JSON in an Android application. After successfully downloading the information, I need to store it in a JSONArray with the tag "Categories" for display in a ListView. Below is the code snippet I a ...

Transform hierarchical DataFrame in pandas into JSON format

My DataFrame in pandas holds hierarchical data from the database where the parent_id column dictates each child's parent. I am attempting to convert this DataFrame into a nested JSON format (refer to section 3 for the desired structure). I have encoun ...

"Encountering a Bad Request Error When Setting Up Power Automate Flow for SharePoint List and Azure DevOps Work Item Integration due to an

I have set up a Power Automate flow to track modifications made on a SharePoint List: https://i.stack.imgur.com/jMDbA.png Here is the response body I receive from the wiql query: https://i.stack.imgur.com/mlWtn.png In order to update the work item if i ...

Sending arguments to browser.executeScript

How can I provide parameters to browser.executeScript static sortableDragAndDropByClassName(dragElementClassName: string, dropElementClassName: string) { return browser.executeScript(function () { console.log(dragElementClassName); conso ...

The issue of losing milliseconds from a timestamp while deserializing into an object with JSON.net is a common

When I deserialize a timestamp from JSON to an object, it seems to lose its millisecond precision. var json = "{\"timestamp\":\"2016-06-16T16:27:36.808Z\"}"; var dict = JsonConvert.DeserializeObject<Dictionary<string, object ...

Express.js Alert: JSON GET Request Invalid

During my API development process, I encountered a complex issue. Whenever I attempt to execute res.send(INSERT JSON) with a Content-Type header of application/json (which is the standard for most AJAX requests), an invalid json error occurs. However, if I ...

Securing routes in Angular2 using authguards

Currently, I am working on developing a web application and facing some difficulties with routes. I have created an AuthGuard to determine if a user is logged in or not. However, the issue arises when I try to categorize routes into two types: - Routes th ...

Expand row size in grid for certain row and item

For my project, I am utilizing a Grid layout to display 5 items per row. https://i.sstatic.net/PW6Gu.png Upon clicking on an item, my goal is to have the item detail enlarge by increasing the size of the HTML element. https://i.sstatic.net/nGj8l.png Is t ...

"Modifying a sub-array within a JSON object using a RESTful API in the MEAN

Having trouble updating a document that is already saved in MongoDB for my MEAN stack application. I've read that using patch instead of post in my REST API paths is the way to go, but it's still a bit unclear to me. Specifically, I need to add a ...

Is it possible for me to create an interface that enables me to invoke a custom method on particular strings?

My database returns objects structured like this: interface Bicycle { id: string; created_at: string; } The data in the created_at field is a machine-friendly date that I need to convert into a Date object for localization: new Date(bike.created_at). ...

Tips on retrieving a strongly typed value from a method using Map<string, object>

Having had experience working with C# for a while, I recently ventured into a Node.js project using TypeScript V3.1.6. It was exciting to discover that TypeScript now supports generics, something I thought I would miss from my C# days. In my C# code, I ha ...

What could be causing my customer directive to malfunction?

My main goal is to dynamically display different pages based on whether the user is logged in or logged out <!-- Display this for logged out users --> <ul *appShowAuthed="false" class="nav navbar-nav pull-xs-right&qu ...

I am currently running the most recent version of AngularFire2. Is there a way to revert back to the earlier version?

Encountering errors with the syntax of the old angularfire2 version while using the latest version (angularfire2 version 4.0.0) pushed me to consider downgrading to a lower version (angularfire2 version 2.0.0). Is there a specific way to do this without ...