Looking to construct a multidimensional array in JavaScript for efficiently reading arrays along with their corresponding options?

I am looking to create a multidimensional array in JavaScript to store questions along with their related options. Here is my current code snippet:

demoArray[i] = new Array();
var id=results.rows.item(i).del_ques_id;
demoArray[i]["question"] = results.rows.item(i).question;
demoArray[i]["id"] = results.rows.item(i).del_ques_id;

tx.executeSql('SELECT option,value,del_opt_id FROM delta_option WHERE del_ques_id='+results.rows.item(i).del_ques_id+' order by value desc', [], getOptionDetails, errorCB);

function getOptionDetails(tx,results){
    console.log("option query");
    var lent = results.rows.length;
    console.log("DEMO table: " + lent + " rows found.");
    for(var j=0;j<lent;j++){
        demoArray[i]=new Array();
        demoArray[i]["option"]=results.rows.item(j).option;
        }
}

I need help with creating an array structure like this within the same demoArray:

1{
  ques: question_string;
  id: question_id;
  option:{
    option_name: option_string;
    option_id: option_id_string;
    }
 }
2{
 ..
 ..
 } and so on

This is the desired structure for my array. Can someone assist me with the code for achieving this?

Answer №1

 let questions = [];
 let questionCounter = 0;
 let options = [];

 function fetchQuestionDetails(tx, results) {
    let length = results.rows.length;
    console.log("Displaying " + length + " rows from the DEMO table.");
    for(let i=0; i<length; i++){
       questionCounter = i;
       questions[i] = new Array();
       questions[i]["question"] = results.rows.item(i).question;
       questions[i]["id"] = results.rows.item(i).del_ques_id;
       tx.executeSql('SELECT option,value,del_opt_id FROM delta_option WHERE del_ques_id='+results.rows.item(i).del_ques_id+' order by value desc', [], fetchOptionDetails, errorCB);
    } 
 } 

 function fetchOptionDetails(tx, results){
   console.log(questions[questionCounter]["question"])
   let optLength = results.rows.length;
   let qOptions = questions[questionCounter]["qOptions"] = [];
   for(let j=0; j<optLength; j++){
      qOptions[j] = [];
      qOptions[j]['optionId'] = results.rows.item(j).del_opt_id;
      qOptions[j]['option'] = results.rows.item(j).option;
      qOptions[j]['optionValue'] = results.rows.item(j).value;
   } 
   console.log(questions[0]["qOptions"][0]["optionId"]);

   $scope.$apply(function() {
      $scope.quesData = questions; 
   });
 }

Hopefully, this information proves to be useful to you!

Answer №2

let demoArray = [];
let question = results.rows.item(i).question;
let id = results.rows.item(i).del_ques_id;
let questionObj = {};

let options = [];
let option = {};

// Perform your query to populate the options. Assuming there are multiple options for a question, loop the next three lines of code for each option
option["option_name"] = "Some name result from your query";
option["option_id"] = "Some id result from your query";

// Add the option to the options array
options.push(option);

// Construct the questionObj with the question, id, and options
questionObj["question"] = question;
questionObj["id"] = id;
questionObj["option"] = options;

// Add the questionObj to the demoArray
demoArray.push(questionObj);

You can now loop through the code above to add multiple questions to your demoArray.

The resulting structure will be something like:

[
{
    question: question_string;
    id: question_id;
    option:[
        {
            option_name: option_string;
            option_id: option_id_string;
        },
        {
            option_name: option_string;
            option_id: option_id_string;
        }
        ....
 }
 {
        ..... Other Question Objects 
        ......
 } and so on

]

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

Error: The React Hook "useX" should not be invoked at the top level of the code

I am facing a challenge while attempting to transfer the exception handling logic from the component to my service class: Login.tsx: import { useSnackbar } from "notistack"; // ... const Login = () => { const { enqueueSnackbar } = useSnack ...

Is there a way I can create a conditional statement to determine the values of my selection?

I need to customize the order status values for 'confirmed', 'on the way' and 'delivered'. How can I map these statuses to specific numerical values based on the options available in a select menu? Confirmed - 10 On the way - ...

What is the method for retrieving a PHP JSON variable value and displaying it in HTML?

Using the graph API, I managed to retrieve my Facebook friend list and received a JSON array as a response. The value of that array is stored in a variable like this: $json_output=($result['summary']['total_count']); echo "$json ...

Converting PDF files to JSON in ASP.NET and transferring them to AngularJS using Base64 does not result in identical files

After encoding a PDF file as Base64 and assigning it to a property of my model object in ASP.NET WEB API, the JSON response is received by my AngularJS client application. However, upon saving the file, I noticed that the file size increases by one and 1/3 ...

Chrome extension causing delays in rendering HTML on webpage

Currently, I am developing a script (extension) that targets a specific HTML tag and performs certain actions on it. The challenge I am facing is that this particular HTML tag gets dynamically loaded onto the page at a certain point in time, and I need to ...

Tailwind not properly filling the full width of the screen despite being a fixed element

Can someone assist me in achieving full-width for a fixed element in Tailwind? Check out the modal screenshot here: Modal Screenshot Please disregard the placeholder text as I am still in the testing phase. My React code: import { Dialog, Transition } f ...

Live Update Google Sheet Data to JSON Without Reloading Web Page

This particular function is executing smoothly. My main concern lies in updating a DOM element without reloading the webpage, if any alterations are made to the data on a Google sheet I am utilizing a JSON file from Google sheets: https://spreadsheets.g ...

Even though I included a key prop for each item, I am still encountering the error message stating that every child in a list should have a distinct "key" prop

I have been trying to retrieve data from a rest API and display it as text on my browser. However, I am encountering the following error: index.js:1 Warning: Each child in a list should have a unique "key" prop. Below is how I have set up the key prop. ...

Changing the value of an object within an array of objects in Codeigniter

I received a query result with values stored in $some = $query->result(). Now I need $some[0] to have the following properties: Name Type (A/B) Status (0/1) However, all objects currently have a null status. I want to set it to 0 if the type is A and ...

After refreshing the page, vuex is encountering null values when using firebase.auth().onAuthStateChanged

Encountering an issue with Vuex and Firebase Authentication integration. When reloading the page, there is a delay in response from firebase.auth().onAuthStateChanged. I require an immediate response upon page reload without using router guards as seen in ...

What could be the reason for Angular to merge the element at index 0 of an array into a subarray instead of doing

After setting up the Array in my oninit function, I encountered an issue where one part of the array was functioning as intended while the other returned an error. this.tests = [{ status: 0, testresults: [{ name: 'test ...

Grabbing specific inline JSON data with jQuery's .getJSON function or a comparable method

I am trying to extract information from an array embedded within a <script> tag using jQuery's .getJSON method. According to the documentation I've come across (http://api.jquery.com/jquery.getjson/), .getJSON typically needs a URL and an e ...

Vite terminal not executing Npm commands

Here is what I entered: npm run dev Error: npm ERR! Missing script: "dev" npm ERR! npm ERR! To see a list of scripts, run: npm ERR! npm run npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\andre\AppData&bs ...

Browser refresh not triggering view update in Rails and ReactJS application

Recently, I integrated Reactjs into my Rails application. Strangely, when I modify the content of a .jsx file and reload it with different text, such as changing from <h1>Hello<h1/> to <h1> Hello again<h1/>, the browser fails to res ...

Email Form Application: Utilizing NodeJs and Express - Error: URL Not Found /

I'm encountering a "cannot GET" error whenever I try to run my application on a live server using VS Code. My assumption is that the issue lies within my routing configuration, but I'm struggling to identify the exact problem. Any assistance woul ...

Error: Headers cannot be set once they have already been sent. I am perplexed as to why this is occurring

I can't seem to pinpoint the source of the problem...After researching the meaning of this error, it appears that I may be either sending a request or response twice somewhere in my code. However, I have thoroughly reviewed my code and cannot find any ...

Modify the div's visibility based on selected option in the dropdown menu

In my PHP file, I have the following codes: <section id="placeOrder"> <h2>Place order</h2> Your details Customer Type: <select name="customerType"> <option value="">Customer Type?</option> <option value="ret ...

Transform your data visualization with Highcharts enhanced with the stylish appearance of DHTML

I am currently using a dhtmlx menu with my charts, specifically the legendItemClick event. It worked perfectly when I was using highcharts 3.0.1. However, after upgrading to version 4.1.7, the function legendMenu_<?=$id?>.showContextMenu(x,y) in the ...

Struggling to pass a function argument as a string for use within the function

Although the title may seem unclear, I will clarify. I have a collection of images on the left side and I have implemented an onclick function on each one to display the image and some information on the right side. It's like having thumbnails on the ...

What steps can I take to ensure the reset button in JavaScript functions properly?

Look at this code snippet: let animalSound = document.getElementById("animalSound"); Reset button functionality: let resetButton = document.querySelector("#reset"); When the reset button is clicked, my console displays null: resetButton.addEvent ...