Angular - Struggling to locate a specific value within an array

Hey everyone, I'm currently struggling with using the find method for arrays.

Here is the code snippet:

I'm facing an issue with the code on line 80, while a similar function on line 69 is working fine.

Error message:

ERROR TypeError: Cannot read property 'customer_fullname' of undefined

The goal is to populate myForm with data from MongoDB. The document contains the following information:

 1. _id:6114e3c1c5934f0fc8da2156
    
 2. fullname:"John Pearson"
    
 3. email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9af0f5f2f4dafdf7fbf3f6b4f9f5f7">[email protected]</a>"
    
 4. address:"Yishun street 69 Blk 420"
    
 5. user_id:"61003363e8ded0257c63592a"

I have used

user_id: this.authService.getUserID()
. After fetching the user id from the auth service, I insert it into myForm as user_id and then attempt to fetch the corresponding fullname from customers since the user_id matches the _id for users.

When I run console.log(this.customers); it displays the following data:

[{…}] 0: address: "Yishun street 69 Blk 420" email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="315b5e595f71565c50585d1f525e5c">[email protected]</a>" fullname: "John Pearson" user_id: "61003363e8ded0257c63592a" _id: "6114e3c1c5934f0fc8da2156" [[Prototype]]: Object length: 1 [[Prototype]]: Array(0)

My objective is to search the customers array based on the user_id. Sorry if my explanation was unclear.

Any assistance would be greatly appreciated. Thank you in advance!

Answer №1

When utilizing ReactiveForms, be sure to use formControlName

<select id='name' name='name' formControlName="user_id"
      (change)="selectChangeHandler($event)">

To assign a value to a FormControl within a FormGroup, utilize setValue method

this.myForm.value.id = this.selectedId;
//I'm uncertain if it should be user_id or id

this.myForm.get('id').setValue(this.selectedId);

If you need to access a property, consider doing it in two steps:

this.myForm.value.customer_fullname =
   this.customers.find(x=>x.user_id===this.myForm.value.user_id)
  .customer_fullname;
const customer=this.customers.find(x=>x.user_id===this.myForm.value.user_id)
this.myForm.get('customer').setValue(
        customer?customer.customer_fullname:null)

If all values are linked to an element in the array using a unique field, you can easily retrieve the element for submission: "customer"

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

PHP code snippet: Calculate the total sum of elements within an array

Here is an example of the array structure: array(2)( ['id'] => "59898441545", ['total'] => array( [0] => 2, [1] => 5 [2] => 10 [3] => 35 ) ); My goal is to transform the 'total' key from an array into the ...

Create a recursive array structure that contains two distinct data types and specific guidelines

I have a unique array structure where the odd index always contains elements of TypeA and the even index always contains elements of TypeB. It is guaranteed that this array will always have an even length, never odd. The data structure of this array must ...

Understanding Pointer Array Dereferencing in the C Programming Language

I'm encountering an issue with this specific segment of code printf("\nIn Func: %s", (*article[ctr]).artname); I am using Code::Blocks and I keep getting the error "undefined reference to WinMain@16". Article is a pointer array, should I not be ...

Restricting HTTP requests to once every 200 milliseconds in Angular 4 with filtering in place

In my current project, I am working on a page that utilizes an ngFor to display an array of objects. One of the features I want to implement is the ability for users to filter these objects by entering specific keywords in an input field. Since the data f ...

Implementing PrimeNG with angular2-seed: A Step-by-Step Guide

I have successfully configured an angular2-seed project, but I am facing challenges while trying to integrate PrimeNG into my environment. My first step was to install Primeng and PrimeUI: npm install primeng --save npm install primeui --save After inst ...

Error encountered in Angular 6 due to an undefined global variable in browser-crypto.js

Currently, I am working on implementing socketjs and have run into an error. https://i.sstatic.net/VRbDT.png The packages I am using for socket and stomp are listed below: import * as SockJS from 'sockjs-client'; import * as Stomp from 's ...

Having trouble getting mongoose, node, and express to work together harmoniously

I am currently following a tutorial on node.js and express from DailyJS but have encountered some confusion. According to the tutorial, I should be adding this code: mongoose = require('mongoose').Mongoose db = mongoose.connect('mongodb: ...

Add a fresh sub-document to the array within the primary structure

I currently have the following Go structs stored in my MongoDB database: type Station struct { ID bson.ObjectId `bson:"_id" json:"id"` Name string `bson:"name" json:"name"` Sensors []Sensor `bson:"sensors" json:"sens ...

What makes TypeScript believe that the variable could possibly be undefined when it is clearly not the case?

I recently encountered an issue where TypeScript incorrectly identifies a variable as possibly being undefined. Here is a simplified example: const func = (val1?: boolean, val2?: boolean) => { if (!val1 && !val2) return; let result: boolean; ...

Tips for efficiently populating a MongoDB database for end-to-end testing

After following the setup process outlined in this guide: https://medium.com/developer-circles-lusaka/how-to-write-an-express-js-server-using-test-driven-development-921dc55aec07, I have configured my environments accordingly. Utilizing the config package ...

Transform the absence of value into an empty string within a function

I currently have a functioning code that I am pleased with and would prefer not to make any major changes, but rather just add a new feature that I require. However, I am unsure of how to go about it... Below is the existing code: const Obj = { "0": ...

What is the best way to combine routes from various modules?

app.module.ts ... imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule, HttpClientModule, RecipesModule ], ... app-routing.module.ts ... const routes: Routes = [ {path: '', redirectTo: &ap ...

MongoDB is currently inactive and not operational

As I was developing an automatic drink dispenser, I encountered an issue after downloading Mongo 3.0.7. Every time I try to run it, I receive the following error: I found inspiration from this website: 2016-02-02T15:56:42.585-0500 E NETWORK [initandlis ...

Issue with PrimeNG Calendar month picker functionality not functioning as expected

I recently integrated a PrimeNG code snippet for a month picker. Although it is functioning correctly, I noticed a discrepancy compared to the PrimeNG example - specifically, the year does not change when clicking on the arrow buttons. The ngModel, howev ...

Mongoose: Executing an additional query on the fetched records

Issue: In my database, I have a collection called 'Groups' which contains embedded documents of 'Members'. My goal is to retrieve a specific Member by their 'MemberID' and gather all their information from the 'Users&apo ...

Using C++ to read a file and store its contents in an array

Struggling with a member function that reads from a file and appends content to an array of Player objects line by line. Originally, passing the testList2 object by reference worked fine. However, the main file cannot be altered, so now the readFile functi ...

Encountering a "Token is not valid or unexpected" issue while trying to import mongoose version 7.3.0

Attempting to establish a connection to a MongoDB Atlas cluster using mongoose has resulted in an error message following a lengthy string of output. /path/node_modules/mongodb/lib/collection.js:74 pkFactory: db.options?.pkFactory ?? utils_1.DE ...

The autocomplete suggestions appear as faded gray text following the cursor in the input field, rather than displaying as a pop-up selection

My website is built using Angular 10 and Angular Material. I am looking to enhance the input suggestions in matInput, but in a unique way that differs from matAutocomplete. Instead of displaying a list of options, I want to show just one suggestion for a ...

Angular 7 error: Form control with name property does not have a valid value accessor

Currently, I am utilizing angular 7 and have a parent and child component set up as demonstrated in the Stackblitz link provided below. Strangely enough, when I assign the formControlName from the child component using "id", everything functions flawlessly ...

Conceal a div when clicked outside using TypeScript with Next.js and Tailwind CSS

I am currently working on a modal using TypeScript, Next.js, and Tailwind CSS. My goal is to hide the modal when I click outside of it. However, I am encountering some errors related to types and other issues in my TSX file. The functionality works perfec ...