Searching through an array based on a specific string

Could someone lend a hand in getting this to function...

The code snippet below is functioning

const acco = [{FullyQualifiedName=(-) Imposto Unico, Id=109, sparse=true, AcctNum=3.1.2.01.03027}, {FullyQualifiedName=13º Salário, Id=114, sparse=true, AcctNum=4.1.2.04.04062}, {Id=94, AcctNum=2.1.3.01.02183, FullyQualifiedName=13º Salário a Pagar, sparse=true}, {Id=90, FullyQualifiedName=Adiantamento de Férias, sparse=true}

var payacc = '2.1.3.01.02183';
var accDC = acco.filter(obj => obj.AcctNum === payacc);
if (accDC.length != 0) {
                var accvalid = accDC[0].AcctNum + ' ' + accDC[0].FullyQualifiedName;
              }
//accvalid = 2.1.3.01.02183 13º Salário a Pagar

However, the following code snippet gives an undefined result

const acco = [{FullyQualifiedName=(-) Imposto Unico, Id=109, sparse=true, AcctNum=3.1.2.01.03027}, {FullyQualifiedName=13º Salário, Id=114, sparse=true, AcctNum=4.1.2.04.04062}, {Id=94, AcctNum=2.1.3.01.02183, FullyQualifiedName=13º Salário a Pagar, sparse=true}, {Id=90, FullyQualifiedName=Adiantamento de Férias, sparse=true}

var payacc = '02183';
var accDC = acco.filter(obj => obj.AcctNum.includes(payacc));
if (accDC.length != 0) {
                var accvalid = accDC[0].AcctNum + ' ' + accDC[0].FullyQualifiedName;
              }

returns TypeError: Cannot read property 'includes' of undefined

I suspect this occurs because there is no AcctNum for the last entry, but how can I bypass this? Apologies if I'm overlooking something too obvious.

Answer №1

Make sure to first verify the existence of o.AcctNum in your filter function. This step will resolve the issue you are facing. Additionally, I have rectified some errors present in your code.

const acco = [
  {FullyQualifiedName : "Imposto Unico", Id:109, sparse:true, AcctNum:"3.1.2.01.03027"},
  {FullyQualifiedName:"13º Salário", Id:114, sparse:true, AcctNum:"4.1.2.04.04062"},
  {Id:94, AcctNum:"2.1.3.01.02183", FullyQualifiedName:"a Pagar", sparse:true},
  {Id:90, FullyQualifiedName:"Adiantamento de Férias", sparse:true}]

var payacc = '2.1.3.01.02183';
var accDC = acco.filter(o => o.AcctNum && o.AcctNum === payacc);
if (accDC.length !== 0) {
                var accvalid = accDC[0].AcctNum + ' ' + accDC[0].FullyQualifiedName;
                 console.log({accvalid})
              }

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

Submitting the form without utilizing Ajax, but instead sending data directly to a PHP script

I've encountered an issue while posting a form to a PHP file using AJAX. Despite my efforts, the form is bypassing AJAX and posting directly to the PHP file. Here is my form: <form id="editform" name="editform" action="ajaxeditform.php" method= ...

Is there a way to add a fade-in and slide-in effect to this dropdown JavaScript, as well as a fade-out and

Although I lack the necessary knowledge of Javascript, I am aware that my request may be a bit much. The code I currently have is directly from the w3school dropdown-list demo. Would it be possible for you to help me implement a fade in and slide in effect ...

The error message "No native build was found for M2 MacBook" appeared while using npm with Node

I encountered this issue while working on my M2 MacBook, which ran smoothly on my older Intel MacBook. Any insights on what might be causing the problem? Using bun, but even running npm run dev (node 18) results in the same error. The same error has also ...

Create a new chart using completely unique information

I am currently working on implementing the example found at http://bl.ocks.org/mbostock/1093130. The goal is to have the "update" function redraw the graph with a completely different dataset each time a button on the DOM is pressed. I have made some modif ...

Handling a change event for a mat-datepicker in Angular 7 can be tricky, especially when its value is tied to an optional input parameter. Let's dive into how to

I've recently started working with angular development and encountered a challenge with a mat-datepicker. The value of the datepicker is connected to filterDate using [(ngModel)] as an @Input() parameter. I have implemented a handleChange event that e ...

Encountering a 400 (Bad Request) error while making a POST request to the server in a MERN

In my reactjs application, I added a button to delete user accounts. When the button is clicked, a form appears where users need to enter their password and click on Delete to confirm. However, when testing this feature, clicking on the Delete button does ...

Cross-Domain Image Uploading

I've been attempting to enable image uploads from one domain to another (CORS). Everything runs smoothly on Localhost, but when I try it on an actual domain, I consistently encounter this message in the Developer Console: Invalid request In my uplo ...

Is there a way to embed HTML code within a JavaScript variable?

Embedding HTML code within Java Flow can be quite interesting For instance: Check out this JSFiddle link And here's how you can incorporate it into your script: widget.value += ""; Generating a Pro Roseic Facebook POP-UP Box through Widg ...

Combining data from multiple API calls in a for loop with AngularJS

I'm working with an API that contains pages from 1 to 10 and my goal is to cycle through these page numbers to make the necessary API calls. app.factory('companies', ['$http', function($http) { var i; for (i = 1; i < 11 ...

Unexpected alteration of property value when using methods like Array.from() or insertAdjacentElement

I'm encountering an issue where a property of my class undergoes an unintended transformation. import { Draggable, DragTarget } from '../Models/eventlisteners'; import { HeroValues } from '../Models/responseModels'; import { Uti ...

Ajax - unable to show posts upon submission

Whenever I submit a post, I am unable to display them and I'm not sure why it's not working. The getPosts() function works fine when I refresh the page. However, after submitting the posts, I can't seem to retrieve them. I am using a JSON fa ...

Unable to utilize a third setState function due to the error message indicating an excessive number of re-renders

My current challenge involves setting an initial state for my Hook. I have a clickable element that changes the state between Decreasing and Increasing upon click, and this part is functioning properly. However, I encounter an issue when attempting to defi ...

Is the behavior of a function with synchronous AJAX (XMLHttpRequest) call in JavaScript (Vanilla, without jQuery) the same as asynchronous?

I'm facing an issue with a file named tst.html and its content: part two (purely for demonstration, no extra markup) The challenge arises when I try to load this file using synchronous AJAX (XMLHttpRequest): function someFunc() { var str = &ap ...

Steps to create a clickable button wrapper label in React

Contained within the components below: <CheckboxGroupLabel htmlFor={option.label}> <FormCheckbox onClick={() => onChange} key={option.label} defaultChecked={defaultChecked} {...rest} /> {option.value} ...

What is the best way to upload images in Vue.js without using base64 formatting?

Is there a way to upload an image file without it being base64 encoded? I currently can only achieve base64 format when trying to upload an image. How can I modify the code to allow for regular file uploads? <script> submitBox = new Vue({ el: "#su ...

Is it possible to transform JSON Array Data from one format to another?

As someone who is new to the software field, I am working with a JSON array of objects: var treeObj = [ { "name": "sriram", "refernce_id": "SAN001", "sponer_id": "SAN000" }, { "name": "neeraja", "r ...

Dependency injection of an Angular app factory toaster is causing the application to malfunction

I am currently working on an Angular application that utilizes Firebase as its backend. My goal is to inject 'toaster' as a dependency within my authorization app factory. Below is the initial setup of the app.factory: app.factory('principa ...

Is it possible to transfer a variable from my javascript code to a jsp file?

Within a HTML file, I have created a variable in JavaScript consisting of an array with two entries - a latitude and a longitude. I am looking to use AJAX to send this variable and then utilize it in my JSP file to populate a form. Does anyone have any su ...

traverse a PHP array with multiple dimensions using a relative path

While working on my website, I encountered an issue with reading JSON data that I'm trying to use. Fetching the data is not a problem: <?php $data = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/cha ...

JQuery Array: How to Prepend Elements to the Beginning

In my scenario, there's an input box labelled #status and a submit button with the class .btn. The requirement is simple: when something is typed into the input field and the button is pressed, I want that text to be added at the beginning of an array ...