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

The subscription data for nested classes appears to be displaying as undefined

In my current project, I am utilizing Angular 8 and facing an issue with a nested class. The problem arises when trying to access data from an observable subscribe operation in the child class (Players) within the main Tournament class. Until the data is r ...

When the local server and SPA are running on different ports, utilizing an authentication cookie can help bridge the

I currently have a nest.js webserver running on localhost:3000, with an angular frontend served to localhost:4200 (using the dev server). These ports are set as defaults. My authentication process involves sending an access-token in a cookie to the front ...

The issue with Rxjs forkJoin not being triggered within an Angular Route Guard

I developed a user permission service that retrieves permissions from the server for a specific user. Additionally, I constructed a route guard that utilizes this service to validate whether the user possesses all the permissions specified in the route. To ...

Generate an alert with a numerical input field - Ionic

How can I create an input with type number in AlertController? I attempted to implement this, but the input only accepts text and not numbers. const alert = this.alertCtrl.create({ title: 'Add Ingredient', inputs: [ { name: ' ...

What is the process for obtaining the result and storing it in an array using M

Recently, I just started exploring angular and ventured into using mongoose with mongodb. Within my application, I require a list of driver names in the form of a string array. However, instead of receiving a simple array of names, I am getting an array o ...

Creating a stacked chart in Angular using chart.js with JSON array of objects values

I am currently working on implementing a stacked chart using chart.js, and I have encountered some challenges: I am struggling to display currency values in the correct format on the chart (the height of the bar is not visible when passing amounts). How c ...

Select the implied type from a resolved Promise type in Typescript

I am working with a function called getStaticProps in Next.js that returns a Promise, resolving to an Object with the following structure: type StaticProps<P> = { props: P; revalidate?: number | boolean; } To generically "unwrap" the type o ...

A method to eliminate the mouse-over effect following the selection of an input box

Currently, I am utilizing Angular and encountering three specific requirements. Initially, there is an input box where I aim to display a placeholder upon pageload as 'TEXT1'. This placeholder should then toggle on mouse hover to display 'TE ...

Confirm that the user has interacted with every input

When it comes to validating a form, you have the ability to determine if a user has interacted with an input field or checkbox (using X.touched). Is there a built-in validator that requires a user to specifically interact with each input field at least onc ...

How can I showcase an image using Angular?

Recently, I've started working with Angular and I'm trying to display images using assets. I have a service that looks like this: const IMAGES = [ {"id":1, "category": "boats", "caption": "View from the boat", "url":"assets/img/boat_01.jpeg"}, ...

How can we add a key:value pair at a specific position in an array in Angular 2 using Typescript?

Is there a way to insert a key value pair at a specific index in an array? I am currently struggling with this task. Here is the code I have been working on: this.quiz.push( { "question-no":this.no, "Ans":this.ans } I require this functionality to ...

Ways to extract the final digit from a format such as an IP address in JavaScript

Is there a way to retrieve the last digits 192.168.1.180 For instance: From the IP address 192.168.1.180, I would like to extract 180. Thank you in advance ...

What is the process for converting an image into base 64 using Angular 5?

Is there a way to convert an image into base 64 using angular5 when the image is sourced from Facebook or Google authentication API? I seem to be encountering an issue, what could I be doing wrong? getBase64Image(img) { var canvas = document.createEleme ...

Using Angular 5 with Typescript to generate and return an array of freshly instantiated typed objects

My backend service provides me with "moments," and I have two functions to handle this data. One is a get() method that returns a single object, and the other is a search() method that returns an array of objects. moment.service.ts The get method success ...

When selecting the "Open Link in New Tab" option in Chrome, the Angular app's routing will automatically redirect to the login page

I am facing a peculiar issue in my Angular 2 application that I need help troubleshooting. Currently, the routing within my app functions as intended when I click on links to navigate between different components. Here is an example of how the routing path ...

Implementing Express.js allows for the seamless casting of interfaces by the body within the request

I have created a similar structure to ASP.NET MVC and uploaded it on my github repository (express-mvc). Everything seems fine, but I am facing an issue with casting the body inside the request object to match any interface. This is what I am aiming for: ...

A guide on connecting multiple select components to a unified Angular 6+ reactive form without triggering redundant updates

I am facing an issue where I need to connect multiple input components to a single angular reactive form, but encounter two main obstacles: By default, only the form in which user input occurs gets updated If I use [(ngModel)] it does work, but it trigge ...

Value is not defined when subscribing to subject in Event Bus Implementation

After creating an EventBusService and EventData, here is the implementation: export class EventData { public eventName: string; public event: any; constructor(eventName: string, event: any) { this.eventName = eventName; this.e ...

Tips for generating a new method using an existing one

Searching for the best practice to inform the ts compiler that a method will be generated at runtime. interface Todo { /* ... */ } export class TodoModel { todos: Todo[] = []; constructor() { //... } bindTodoListChanged(callback : (todos: Todo[]) ...

I'm having trouble with ViewChild - consider upgrading to beta7 for a solution

import {Page,NavController,NavParams,Platform,IonicApp} from 'ionic-angular'; import {ViewChild} from '@angular/core'; @Page({ templateUrl: 'build/pages/tabspage/tabspage.html' }) @ViewChild('myTabs') tabRef: T ...