Experiencing difficulty trying to access an element in an array that is either one index higher or lower than the current index within a for loop, despite the element's presence

In the array of elements known as my object idAry, each element has a property called msisdn_id. The array contains 4 objects. While looping through them, if the ID matches the second ID in the loop, it correctly falls into the else clause. However, trying to access IDs of elements that are one position before or after the current element results in an error stating

[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'msisdn_id' of undefined"
. It's puzzling why this property is suddenly undefined when I'm clearly iterating through its adjacent elements as well.

The code snippet in question is:

for (let [index, val] of idAry.entries()) {
    console.log("index is:" + index);
    console.log("val[index].msisdn_id:" + val[index].msisdn_id);
    if(id == val[index].msisdn_id){
      console.log("id found:" + val[index].msisdn_id);
      if( index == 0 ){
        //no left button
        console.log("index == 0: " + val[index + 1].msisdn_id);
        this.rightId = val[index + 1].msisdn_id;
      }
      else if (index == (val.length - 1)) {
        //no right button
        console.log("else if: " + val[index - 1].msisdn_id);
        this.leftId = val[index - 1].msisdn_id;
      } 
      else {
        console.log("both LR: " + val[index - 1].msisdn_id + "," + val[index + 1].msisdn_id);
        this.leftId = val[index - 1].msisdn_id;
        this.rightId = val[index + 1].msisdn_id;
      }
      break;
    }
  }

The output generated looks like this:

length of ary is:4
TerminalProfileReport.vue?3387:400 index is:0
TerminalProfileReport.vue?3387:401 val[index].msisdn_id:111
TerminalProfileReport.vue?3387:400 index is:1
TerminalProfileReport.vue?3387:401 val[index].msisdn_id:222
TerminalProfileReport.vue?3387:403 id found:222

A correction was made to the output which initially displayed val[index]. The updated code appears as follows:

for (let [index, val] of idAry.entries()) {
    console.log("index is:" + index);
    console.log("idAry[index].msisdn_id:" + val.msisdn_id);
    if(id == val.msisdn_id){
      console.log("id found:" + val.msisdn_id);
      if( index == 0 ){
        //no left button
        console.log("index == 0: " + idAry[index + 1].msisdn_id);
        this.rightId = idAry[index + 1].msisdn_id;
      }
      else if (index == (idAry.length - 1)) {
        //no right button
        console.log("else if: " + idAry[index - 1].msisdn_id);
        this.leftId = idAry[index - 1].msisdn_id;
      } 
      else {
        console.log("both LR: " + idAry[index - 1].msisdn_id + "," + idAry[index + 1].msisdn_id);
        this.leftId = idAry[index - 1].msisdn_id;
        this.rightId = idAry[index + 1].msisdn_id;
      }
      break;
    }
  }

Answer №1

It seems like there is some confusion between val and idAry. Remember, val[index].msisdn_id does not exist; you should use val.msisdn_id instead.

for (let [index, val] of idAry.entries())
  {
  console.log("index is:" + index);
  console.log("val.msisdn_id:" + val.msisdn_id);


  if( id == val.msisdn_id)
    {
    console.log("id found:" + val.msisdn_id);
    if( index == 0 )
      {
      //no left button
      console.log("index == 0: " + idAry[index + 1].msisdn_id);
      this.rightId = idAry[index + 1].msisdn_id;
      }
    else if (index == (idAry.length - 1)) 
      {
      //no right button
      console.log("else if: " + idAry[index - 1].msisdn_id);
      this.leftId = idAry[index - 1].msisdn_id;
      } 
    else
      {
      console.log("both LR: " + val[index - 1].msisdn_id + "," + val[index + 1].msisdn_id);
      this.leftId = idAry[index - 1].msisdn_id;
      this.rightId = idAry[index + 1].msisdn_id;
      }
    break;
    }
  }

However, there is a much simpler way to achieve the same result.
Check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex, it can make your life easier.

let index = idAry.findIndex(e=>e.msisdn_id===id)

if (index!=-1)  // if exist
  {
  console.log('id found , index is', index, idAry[index].msisdn_id);

  if ( index > 0 )
    { this.leftId  = idAry[index - 1].msisdn_id;}

  if (index < (idAry.length - 1))
    { this.rightId = idAry[index + 1].msisdn_id; }
  }
else
  {
  console.log('id not found (', id , ')' );
  }

Answer №2

It's uncertain if the code provided matches the one in use, especially since the logs mentioned differ between idAry[index].msisdn_id and val[index].msisdn_id:. However, judging from the code snippet in the question, the problem appears to stem from how the variable val is being utilized as it represents the array itself. In each loop iteration, val corresponds to the value of an entry within the idAry array.

for (let [index, val] of idAry.entries()) {
    console.log("index is:" + index);
    console.log("idAry[index].msisdn_id:" + val.msisdn_id);
    if(id == val.msisdn_id){
      console.log("id found:" + val.msisdn_id);
      if( index == 0 ){
        //no left button
        console.log("index == 0: " + idAry[index + 1].msisdn_id);
        this.rightId = idAry[index + 1].msisdn_id;
      }
      else if (index == (idAry.length - 1)) {
        //no right button
        console.log("else if: " + idAry[index - 1].msisdn_id);
        this.leftId = idAry[index - 1].msisdn_id;
      } 
      else {
        console.log("both LR: " + idAry[index - 1].msisdn_id + "," + idAry[index + 1].msisdn_id);
        this.leftId = val[index - 1].msisdn_id;
        this.rightId = val[index + 1].msisdn_id;
      }
      break;
    }
  }

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

Combining numerical values within an array using JavaScript

Below are different buttons ranging from 1 to 9 that I have: <button type="button" onclick="calculatorNumber(1)"> When clicked, the following function is triggered: function calculatorNumber(i) { myNumbers.push(i); var x = document.getElem ...

Issue with encoding value in Firestore when inserting a document using Promise.all() alongside MongoDB Insert

Initially, I had the following piece of code: const userObject = { name: "username", id: "FirebaseUID", posts: [] } await Promise.all([ admin.firestore().collection("users").doc("FirebaseUID").set(userObject), ...

JavaScript will not be passed down to loaded content

Let's say I have two files: main.php additional-content.php In the main.php file, that's where I include my CSS and JS: <head><link href="css/style.css" rel="stylesheet" type="text/css" /></head> <body><script src=" ...

Checking for the existence of a row in Node.js using Sqlite3

Wondering if it's possible to verify the existence of a row using node.js and the sqlite module. I currently have this function in place, but it always returns false due to the asynchronous nature of the module. function checkIfRowExists(username, pa ...

Return an unspecified value when using Array.map function

How can I prevent this map from returning undefined? var onCompareSelectedClick = function () { var talentProfileInfoForAppliedResources = appliedResourcesEntries.map(function(res) { console.log(res); if(res.c ...

The Bootstrap Modal consistently shows the contents of the first record when used within a SQL While Statement

As a newcomer, I am in the process of converting an operational Bootstrap modal that houses a post form. Initially, the modal would open using a button with a specific Id and would always display the FORM contents from the first record found in the SQL w ...

Is there anyone who can assist with rectifying the syntax in Laravel View?

Can you help me with correcting the syntax in my Laravel view? I am trying to display Ajax data in my view and add charts directly in the view without involving the controller. I am familiar with the guidelines for using ConsoleTVs\Charts\Facades ...

Error 1:1 Encountered parsing issue: Unanticipated character ''

I'm still getting acquainted with JavaScript, so please bear with me if this question seems a bit basic. I've been attempting to execute Firebase deploy but keep encountering this error message: 1:1 error Parsing error: Unexpected character ...

Show dropdown menu on bootstrap responsive table

I've encountered an issue with a bootstrap3 responsive table that includes dropdown selections in each row. When the dropdown is clicked, users have to scroll to view all the options, especially on smaller screens where scrolling becomes impossible. ...

Setting a default axios header in Next.js after a user logs in

Currently, in my Next.js app, I have an API route that sets a JWT as a cookie. Axios is being used to fetch data from external APIs and after a user logs in, the JWT needs to be included as a default request header for authentication purposes. The workflow ...

What are the best ways to personalize the Ant Design table and pagination component?

Is there a way to customize and design table and pagination components? Specifically, I am looking to set the header color of the table as green. How can this be achieved? Similarly, for the pagination component, I want to have a background color on page n ...

Displaying an array of JSON objects in ReactJS by parsing them

Recently, I've encountered an odd issue with my React App. I am attempting to parse a JSON object that includes arrays of data. The structure of the data looks something like this: {"Place":"San Francisco","Country":"USA", "Author":{"Name":"xyz", "Ti ...

React: Modifying a common state in one child component causes unintended consequences in other components

Struggling to create a code snippet that enables dynamic rule creation for Trading strategies. However, when it comes to selecting Indicators to utilize, I've encountered a bit of a roadblock. Knowledge of Trading is unnecessary to assist me with this ...

Angular 4: Unhandled error occurred: TypeError - X does not exist as a constructor

I am currently developing a project in Angular 4, and I encountered an error while running the application. The specific error message is as follows - ERROR Error: Uncaught (in promise): TypeError: index_1.EmployeeBase is not a constructor TypeError: in ...

Use Q.js's Q.all() method when dealing with an array of promises of unknown length

I am looking to retrieve an array of promises using Q.all(); such as the code snippet below: return Q.all([ list[0].getCssValue('height'), list[1].getCssValue('height'), ..., lis ...

JavaScript Auto-Closing Modal Pop-Up in HTML

I am looking to implement a feature similar to what is seen on Banks or American Express websites, where a MODAL Popup notifies users that their session is about to expire. In addition to this, I would like to include an "Auto-Close" Popup event that will ...

Why does obj.attr('id') give undefined while obj.getAttribute('id') returns a value?

Why does obj.getAttribute('...') work for me in my JavaScript code, but not obj.attr('...') and obj.prop('...')? I am confused about this issue. Can someone please explain it to me? function ShowTips(obj) // show tip in elem ...

What steps should I take to ensure my .js.erb files are compatible with Rails 7?

I have been following a Rails Tutorial on Building a Link Shortener with Rails 6 and Ruby 2.xx to create an app. However, I am using Rails 7.0.4 and Ruby 3.0.0. I encountered an issue with my create.js.erb file not functioning properly. After some research ...

Looking to Query in Angular with Firebase?

In my TypeScript file, I have implemented a query to the Angular Firebase database. import { Component, OnInit } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/datab ...

Connect Tasks and Lists in Meteor Todo app

I'm currently developing a task management application using the Meteor tutorial as a reference. I have created lists based on the task model, but I am struggling to figure out how to connect them and display all tasks associated with a specific list ...