Add an array into another array using a for loop, with the first result being duplicated

In this loop, I am facing an issue while trying to insert an array into another array. Here is the code snippet:

function convertFormToArray(form){
    var temp={};
    var question={};
    var allQuestions=[];
    
    for (i = 0; i < form.length; i++) {

        // Below line is causing an issue
        temp['question_id'] = form[i].name.substring(13)
        temp['answer'] = form[i].value;
        temp['id'] = 0;
        
        question['question'] =temp;
        allQuestions.push(question);
    }

    return allQuestions;
}

The problem here is that it returns the first result repeated multiple times.

Example of a returned value:

[
    {'question': {'question_id': 4, 'answer': 'AA'...}},
    {'question': {'question_id': 4, 'answer': 'AA'...}}
]

Can you identify the issue with this loop?

Answer №1

This code snippet provides a safer and more readable way to convert form data into an array.

See the demo in action

function formToArr(frm){
  var AllAnnotationsQues=[];

  for (var i = 0; i < frm.length; i++) {
    AllAnnotationsQues.push({
      'AnnotationsQues': {
        'ques_id': frm[i].name.substring(13),
        'ans': frm[i].value, 
        'id':0 
      }
    });
  }
  return AllAnnotationsQues; 
}

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 is the method to display a group label using ng-table?

Does anyone have experience creating a group in ng-table? <div> <div ng-controller="ContractsController" style="position: relative;background:whitesmoke; border:1px solid lightgray; border-radius:5px; margin-top:0px; margin-bottom:5px; h ...

Selenium with JavaScript: The Battle of Anonymous Functions and Named Functions

When working with Selenium JavaScript, the prevalent advice I come across online suggests that the most effective approach to handle the asynchronous behavior of JavaScript is by utilizing anonymous functions with .then() for locating/interacting with elem ...

Is it possible to encounter an invalid character when trying to parse valid JSON using

I have an object with properties that contain JSON strings. When I serialize this object, I get the following string: [{ "template": 1, "action_json": "{\"id\":\"1\",\"action\":\"An action for all of IT!\",& ...

Rearranging the order of Div elements within a main container using JavaScript DOM manipulation

How can I move elements within a div from the start to the end in the same div, for example, changing the order from 1-2-3 to 2-3-1? My code: const cards = document.querySelectorAll(".card"); const firstCard = document.querySelectorAll(".card")[0].inne ...

jQuery problem with setting and redirecting users if cookie value is missing

On my home page, there is a script that checks two things when a user visits our site: If the screen size is less than 800 pixels, they are redirected to the mobile site. If they have previously visited the mobile site and selected "View Full Site," ...

Executing pure JavaScript code in Grails using Groovy

this is a duplicate of Executing groovy statements in JavaScript sources in Grails with a slight variation, my intention is to only render the js-code without enclosing it in script tags picture someone loading a script from my server within their html l ...

Unusual CSS hierarchy observed post AJAX content load

Currently, I am facing a puzzling issue where my CSS rules seem to be losing precedence on a page loaded via AJAX. Despite placing my custom CSS file last in the main page, allowing it to take precedence over any bootstrap styles, after loading new content ...

Maximizing the Use of Multiple Conditions for Styling in AngularJS

I have a table where I need to set different colors based on the values in one of the columns. I've successfully managed to set two colors using NgClass, but I'm unsure how to set up three different conditions. <scri ...

Tips for extracting variables from a get OData call function

Is there a better approach to retrieving variables from a GET OData call? I'm struggling with extracting the 'id' variable from the call within my method. I've tried using callbacks, but have not been successful. Do you have any suggest ...

Setting Up the Columns of an Array in Java

I am working with three arrays of equal lengths that I plan to combine (as they will be sorted based on column c later): double xyz[][] = { Arrays.copyOf(x, x.length), Arrays.copyOf(y, x.length), Arrays.copyOf(z, x.length) }; Upon calling Sy ...

What is the expected return type in TypeScript of a function that returns a void function?

I recently received feedback during a code review suggesting that I add return type values to my functions. However, I am unsure of what return type to assign to this particular function: function mysteryTypeFunction(): mysteryType { return function() ...

Order a set of date strings in an array using JavaScript

Despite my attempts with underscorejs, I found that the min and max methods cannot handle strings as they return infinite. Is there a way around this limitation? Here is a sample array: dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"] ...

Leverage AJAX data to dynamically generate an input field within a Laravel application

. Hey everyone, I'm currently working on implementing ajax for a search functionality. The goal is to display links to the search results' pages along with checkboxes next to each result, allowing users to select orders for printing. Although I ...

Having trouble with Angular 2's Output/emit() function not functioning properly

Struggling to understand why I am unable to send or receive some data. The toggleNavigation() function is triggering, but unsure if the .emit() method is actually functioning as intended. My end goal is to collapse and expand the navigation menu, but for ...

Ways to pass a message from index.html to a Vue.js 3 instance

Picture this scenario: You have a Vue index.html file that also loads a custom script: <!DOCTYPE html> <html lang="en"> <head> ... ... <script type="text/javascript"> languagePluginLoader.then(fun ...

Angular UI Grid failing to properly display date formatting

Currently, I am using Angular's UI Grid to showcase multiple columns. However, I am facing an issue with formatting the date column. The date is being displayed as /Date(1451346632162-0000)/, and similar formats. I have attempted to apply filters in ...

Can a Vue computed property return a promise value?

I have a specific computed property in my code that triggers an API request and retrieves the required data: async ingredients() { const url = "/api/ingredients"; const request = new Request(url, { method: "GET", credentials: "same-or ...

Is it possible for you to simulate the shift key being pressed prior to the event execution?

Is there a way to allow the user to scroll left and right horizontally without having to hold the shift key down? I want to achieve this effect by setting the "shiftKey" variable to true even when it is not physically pressed. Any suggestions on how to ...

Could Ramda assist in enhancing pipeline/composition processes with a logging feature?

Considering implementing logging within a composed chain of functions, the following code demonstrates how it can be achieved: const f = R.compose( transformation2, doAlso(x => console.log(`id: ${x.id}`)), transformation1 ) This approach would c ...

Guide to designing a unique shape in JointJs by combining multiple basic shapes together

Is there a way to combine different shapes in Joint JS, such as creating a custom shape that includes both a rectangle and a circle? I am aware of the path method, but I'm not sure if it is suitable for creating combined shapes like this. ...