Somehow, my array only manages to traverse exactly half of its elements

Something odd is happening with my input tag in the HTML file where only half of my array elements are being processed. The input collects numbers/letters and assigns a line of code, like this:

let result  = Object.fromEntries(
  Object.entries(answers2).map(([k, v]) => [k, MSamples[v] ])
);

For example, if you enter "asdf", it would correspond to:


0: ['M20']
1: ['M30']
2:['M40']
3: ['M50']
length 4

So, in a for loop:

  for (let i = 0; i < Object.keys(result).length; i++) { }

But strangely enough, only part of the output is being displayed:

0: ['M20']
1: ['M30']

Even when removing all other code within the for statement and just keeping a console.log('wow'), it still only logs "wow" twice.

Some people asked for a reproducible example, so here's everything you need:

var MSamples = {
  "A": [
    "M10",
  ],
  "B": [
    "M20",
  ],
  "C": [
    "M30",
  ],
  "D": [
    'M40',
  ],
}

var answers2 = document.getElementById('fname').value;

let result = Object.fromEntries(
  Object.entries(answers2).map(([k, v]) => [k, MSamples[v]])
);

for (let i = 0; i < Object.keys(result).length; i++) {
  console.log('wow');
}
<form class="form1 " action="">
  <input type="text" id="fname" name="fname" value="ABCD">
</form>

After some investigation:

It appears that the issue arises when I include i++; at the end of my for statement. Removing all instances of i++; resolved the problem and everything worked as expected.

Answer №1

I wasn't able to replicate this issue exactly with the provided example, but I have a hunch about what might be happening. Is it possible that there is another element in your DOM with the same id fname?

When you use document.getElementById('fname'), it will grab the first element it finds with that id. If that element's value is only two characters long, then your for-loop will base its logic on that length.

Answer №2

It appears that the issue lies in my inability to include i++; within my code. By removing all instances of i++;, the problem was resolved. I realized that placing it at the end of my for statement caused conflicts.

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

What are some ways to enhance the functionality of the initComplete feature in Dat

$('#example').dataTable( { "initComplete": function(settings, json) { alert( 'DataTables has finished its initialisation.' ); } } ); Is there a way to extend the initComplete function for other languages? $.extend( true, $.f ...

Choosing HTML elements within nested DIV tags

In the process of creating a Hangman-style game using javascript/jQuery, I encountered an issue with selecting HTML content from virtual keyboard keys : <div class="square keyboard"> <div class="content"> <div class="table"> ...

Heroku Internal Server Error with NextJs version 5.0.0

Below are the scripts that I am using: "scripts": { "dev": "node server.js", "build": "next build", "start": "NODE_ENV=production node server.js", "heroku-postbuild": "next build" }, This is the content of my procfile: web: npm start ...

When the user clicks, I plan to switch the audio source

I am looking to update the audio source when a button is clicked, but I am having trouble getting it to work. image description data() { return { audioSrc: '' } }, methods: { setActiveAudio(item) { this.$refs.audioE ...

Reactjs is having issues with Datatable functions

I am making use of the Datatable Library for creating tables easily. After fetching data with the Fetch API and rendering it to the table, everything seems to work smoothly. However, I am facing issues with DataTable Functions such as sorting, searching, ...

What is the best way to extract a message as an object from a JSON data in discord.js?

Currently in the process of developing a discord bot with an election feature for my server's moderator. All the necessary election data is being saved in an external JSON file to ensure that if the bot crashes during an election, it can seamlessly re ...

What is preventing Backbone from triggering a basic route [and executing its related function]?

Presenting My Router: var MyRouter = Backbone.Router.extend({ initialize: function(){ Backbone.history.start({ pushState:true }); }, routes: { 'hello' : 'sayHello' }, sayHello: function(){ al ...

JavaScript filename

This question may appear simple, but I believe the answer is not as straightforward. Here it goes: Should I keep the filename of jQuery as "jquery-1.3.2.min.js" for compatibility reasons, or should I rename it to jquery.js? In my opinion, it's best ...

Unable to simultaneously execute TypeScript and nodemon

Currently, I am in the process of developing a RESTful API using Node.js, Express, and TypeScript. To facilitate this, I have already installed all the necessary dependencies, including nodemon. In my TypeScript configuration file, I made a modification to ...

Selecting the checkbox will activate the POST endpoint

I am working on a nodejs/express app and looking for a way to update my database using a POST route when a checkbox is clicked. The challenge I am facing is that I want to avoid using a submit button or jQuery. I am currently using a Bootstrap4 checkbox ...

Ways to prevent mouse selection in an input field without disabling or making it read-only

Imagine this scenario: <input type="text"> The task at hand is to prevent text selection within the <input> field. ...

A guide to tracing a button click with a personalized <img> tag in Google Tag Manager

Recently, a marketing firm provided me with a custom tag to implement on a Wordpress site for tracking clicks on specific buttons. I am utilizing the Elementor page builder and have assigned unique IDs to each button. Although I am new to Google Tag Manage ...

Steps to send an array through the $_POST array using form.serialize() in ajax

How can I send an array within the $_POST array using AJAX with form data like this: array('name'=>'test','accom'=>array(0=>'test2'.1=>'test3')): $.ajax({ url : 'add_ ...

Having trouble retrieving the value of a custom directive attribute

My custom directive, named "mycomponent", has the following configuration: restrict: 'AE', templateUrl: 'template.html', scope:{ sTransactionType: '=transactionType', sStorageVariable: '=storageVariable&apos ...

Implementing JSON methods in C# WebService to enable communication with external servers

Is it possible to integrate an asp.net web service written in C# into an HTML5/JavaScript website? The challenge is that the web service and client are located on different domains, requiring a cross-domain request. ...

Updating the ID's of nested elements in JavaScript when duplicating an element

After a fruitless search on Google, I have turned to the experts on SO for assistance. The challenge: Create a duplicate of a dropdown menu and an input field with the click of a button (which can be done multiple times) The proposed solution: Implement ...

Scrolling the y-axis with a fixed height limit to prevent overflow

My current dilemma is a seemingly simple one: <div class="container"> <div class="a"></div> <div class="b"></div> <div class="c"></div> </div>​ Within the container, there are 3 divs: A and B ...

Tips for preventing the ng-click event of a table row from being triggered when you specifically want to activate the ng-click event of a checkbox

So, I've got this situation where when clicking on a Table Row, it opens a modal thanks to ng-click. <tr ng-repeat="cpPortfolioItem in cpPortfolioTitles" ng-click="viewIndividualDetailsByTitle(cpPortfolioItem)"> But now, there&apos ...

Set the background color of the Material UI Drawer component

Need some advice on changing the background color of Material UI's Drawer. I've attempted the following approach, but it's not producing the desired result. <Drawer style={customStyle} open={this.state.menuOpened} docked={false} ...

Check if a given string conforms to the JSONATA expression format

Here's the scenario: A user inputs a JSONATA expression into a form field. The form should show an error message if the entered JSONATA expression is invalid. Is there a regular expression or pattern that can determine the validity of a string as a ...