The function `find()` will not provide any data, it will only output `undefined`

I am trying to extract the `s_id` field from this JSON data:

 {
        "StatusCode": 0,
        "StatusMessage": "OK",
        "StatusDescription": [
             {
                "s_id": "11E8C70C8A5D78888E6EFA163EBBBC1D",
                "s_serial": "PkMGo",
                "active": 0,
              },
             {
                "s_id": "11E8C70FB9D10DB38E6EFA163EBBBC1D",
                "s_serial": "UgooX",
                "active": 0,
                },
              {
                "s_id": "11E8C7179F85836D8E6EFA163EBBBC1D",
                "s_serial": "IiLnM",
                "active": 0,
                }, .....
            {
                "s_id": "11E8C71905123F1A8E6EFA163EBBBC1D",
                "s_serial": "LVpcP",
                "active": 0,
             }
              }]}

Despite my efforts, I am unable to find it and keep getting 'undefined'.

 sensors: Sensors[]=[];
 hbp: HBP;
 sensor: Sensors;

     this.ss.getAllS().subscribe(
          sensors => {
            this.sensors = sensors 
            let ss = this.sensors.find(x => x.s_id ===  this.hbp.s_id);
            console.log(ss)
            if (ss) {
              this.selectedSensor = ss.s_id
            }
          }
        );

In addition,

 selectedSensor : string = this.sensors.filter(
    x => x.s_id === this.sensor.s_id[0])
    .map(y => y.s_serial).join('');

I believe there is an issue with this line:

        let ss = this.sensors.find(x => x.s_id ===  this.hbp.s_id);

This may be because the `hbp` variable returns the following JSON:

active: 0
homebox_id: "11E8C71154CC8C188E6EFA163EBBBC1D"
sensors: Array(2)
0: {s_serial: "s_id", s_id: "11E8C70C8A5D78888E6EFA163EBBBC1D"}
1: {s_serial: "UgooX", s_id: "11E8C70FB9D10DB38E6EFA163EBBBC1D"}

Thus, the search might be conducted within these sensors.

The selectedSensor variable is utilized in the HTML code as follows:

<input formControlName="s_id" type="text" placeholder="Select " [(ngModel)]="selectedSensor" aria-label="Number" matInput
            [matAutocomplete]="auto">

How can I retrieve the required data?

Any suggestions or ideas would be greatly appreciated. Thank you!

Answer №1

From my observation, your code appears to be correct. However, it is crucial to verify that the this.ss.getAllS() method is indeed returning an array of StatusDescription types. I suggest conducting a runtime check on the content of the sensors variable to ensure its accuracy.

Answer №2

At first, the sensors in question will be null, making it impossible to access any properties for comparison.

To work around this issue, perform a quick null check on the sensors before proceeding with your search:

this.ss.getAllS().subscribe(sensors => {
  if (sensors) {
    this.selectedSensor = this.sensors.find(x => x.s_id === this.hbp.s_id)
  }
});

If you'd like to see an example using StackBlitz, check out: https://stackblitz.com/edit/select-id-from-observable

Answer №3

To utilize the find function, you can follow the example below:

  let ss =   this.sensors.find((item) => {
      return item.s_id === this.hbp.s_idl
    })


if (ss) {
    this.selectedSensor = ss.s_id         
      }

If you need to combine filter, map, and join operations, ensure that you are returning the item.property within the map function.

.filter((item) => {
  return item.s_id ===  ss.s_id
}).map(
  (item) => {
    return item.s_serial
  }
).join( )

Take a look at this code snippet for reference:

https://stackblitz.com/edit/arrayfind?file=index.js

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

Guide on creating a 4-point perspective transform with HTML5 canvas and three.js

First off, here's a visual representation of my objective: https://i.stack.imgur.com/5Uo1h.png (Credit for the photo: ) The concise question How can I use HTML5 video & canvas to execute a 4-point perspective transform in order to display only ...

Create a unique type in Typescript that represents a file name with its corresponding extension

Is there a way for me to specify the type of a filename field in my object? The file name will consist of a string representing the name of the uploaded file along with its extension. For instance: { icon: "my_icon.svg" } I am looking for a ...

What is the best way to extract the ID from an event in TypeScript?

HTML Code: <ion-checkbox color="dark" checked="false" id="1on" (ionChange)="onTap($event)" ></ion-checkbox> TypeScript Code: onTap(e) { console.log(e); console.log(e.checked); } I am trying to retrieve the id of the checkbox. H ...

Analyzing the value of a tab with Protractor测试

Below is my HTML code showcasing a list of tabs: <mat-tab-group> <mat-tab label="A"> <app-A></app-A> </mat-tab> <mat-tab label="B"> <app-B></app-B> </mat ...

Creating a default option of "please select" on an Angular select element with a null value for validation

Within my Angular application, I am using a select element with an ngFor loop: <select formControlName="type" required> <option *ngFor="let type of typeList" [ngValue]="type.value">{{ type.caption }}</option> </select> When view ...

Conceal the header on signup and login pages using Material UI

I am working on a project with three pages: SignUp, Login, and Lists, along with a header component. My goal is to hide the header on the SignUp and Login pages, and only show it on the List page. Any suggestions on how I can achieve this? Here is my cod ...

DateAdapter not found within Angular/Material/Datepicker - Provider not available

I need assistance with: angular / material / datepicker. My test project is running smoothly and consists of the following files: /src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from ' ...

Customizing the appearance of the Material UI MuiClockPicker with unique style

I am wondering how I can override the styles for MuiClockPicker? I discovered that using createTheme to override the styles actually works for me, but I encountered an error from TypeScript: TS2322: Type '{ MuiOutlinedInput: { styleOverrides: { roo ...

What is the best way to incorporate cors modules in TypeScript?

I am encountering some difficulties while attempting to import the cors module in a TypeScript project using Express. When I use the following code: import cors from "cors"; I receive the following error message: "Cannot find module &apos ...

Visual Studio - TypeScript project synchronization issue

Currently using the 2015 version of Visual Studio Community, I am facing an issue while working on a typescript project. Whenever I make modifications to the code, debug it, and save it using ctrl + s followed by refreshing the browser with ctrl + r, the c ...

Customizing tsconfig.json: Enhancing an existing object by adding new keys in TypeScript

Is it possible to achieve the following functionality by default? let j = {a:1}; j.b = 2; I am aware that there are alternative solutions, but I am curious if this specific task can be accomplished by solely modifying tsconfig.json? ...

Encountering Issue: Unable to locate control with the given name in Angular when generating Dynamic Form with FormGroup

As a beginner in Angular, I aim to develop a dynamic Survey Form that can adjust its questions and input types based on the area. These changes are fetched as JSON data through API calls. Here is the relevant code snippet: .ts File export class Maintenan ...

Comparing Input and Output Event Binding

Can you provide reasons why using @Output for events is more advantageous than passing an @Input function in Angular 2+? Utilizing @Input: Parent Template: <my-component [customEventFunction]=myFunction></my-component> Inside parent-compone ...

Guide to integrating location-based QR code verification

Currently, I am developing an Angular application where I am utilizing an npm package to generate QR codes. One of my main requirements is to incorporate location-based functionality into the QR code system. For instance, if a user is at a specific hotel a ...

The optimal time to register for events within the Vue lifecycle

Currently, I am developing a Vue2 component using vue-component that includes a subcomponent. Here is an example: <note :bus="bus" :itemId="selectedId"></note> The subcomponent contains the following code snippet: <textarea v-model="text" ...

Error: Unable to access the 'nom_gr' property of null - encountered in Chrome

<ion-col col-9 class="sildes"> <ion-slides slidesPerView="{{nbPerPage}}" spaceBetween="5"> <ion-slide *ngFor="let slide of lesClassrooms; let i = index" (click)="saveCurrentSlide(i)"> ...

Incorporating External JavaScript and CSS specifically for a single component

In my Angular 4 application, I have a specific component that requires the use of a js and css file. While most guidelines suggest placing these files in the Index.html file, I prefer to only load them when this particular component is accessed, not on e ...

Utilizing Angular's microservice architecture to dynamically load modules from a provided

Recently, I've been contemplating the best way to integrate Angular into a microservices architecture. Imagine we have separate services for login, user management, and media browsing, adding, and editing - each with its own backend and frontend in i ...

Testing server sent events with Angular solely using Karma-Jasmine

I am currently developing a web application using Angular for the frontend and Python for the backend. My implementation involves utilizing server-sent events (SSE) to stream data from the server to the user interface. While everything is functioning prope ...

Setting up angular-cli project for rc5- Step by step guide

Trying to integrate angular-cli with angular 2 rc5 but facing challenges: The issue of 'Promise' not being found After attempting to install 'npm install -g angular-cli@webpack', typings did not get installed, resulting in WebStorm un ...