Disappearance of array data

I have been working on creating an array of objects with nested arrays, but I am facing an issue where data seems to go missing in the final step:

const args_arr = [];
const options_arr = [];
let options = '';

let text = "";
for (let i = 0; i < 5; i++) {
  for (let j = 0; j < 5; j++) {
    if (i === j) {
      args_arr.push(true);
    } else {
      args_arr.push(false);
    }
  }
  text += args_arr + "<br>";
  options = {
    op1: true,
    op2: false,
    args: ['visible']
  };
  text += JSON.stringify(options) + "<br>";
  options.args.push(args_arr);
  text += JSON.stringify(options) + "<br>";
  options_arr.push(options);

  args_arr.length = 0;
}
text += '<br>' + JSON.stringify(options_arr) + "<br>";

document.getElementById("demo").innerHTML = text;
<pre id="demo"></pre>

All my code appears to be running correctly, except at the last stage when adding options to options_arr, some arrays after 'visible' are disappearing.

This is the outcome I'm observing:

true,false,false,false,false
{"op1":true,"op2":false,"args":["visible"]}
{"op1":true,"op2":false,"args":["visible", [true,false,false,false,false]]}
...

Can you help me identify what might be causing this issue?

Answer №1

The issue arises when pushing the elements from args_arr into options_arr and then making modifications to the information.

To resolve this, replace options.args.push(args_arr); with

options.args.push([...args_arr]);

This change will create a new array with values copied from args_arr, preventing it from being reset during each iteration.

Answer №2

Make sure to create a new args_arr for each iteration

const options_arr = [];
let options = '';
let text = [];
let args_arr = [];
for (let i = 0; i < 5; i++) {
  for (let j = 0; j < 5; j++) {
    if (i === j) {
      args_arr.push(true);
    } else {
      args_arr.push(false);
    }
  }
  text.push(args_arr);
  let options = {
    op1: true,
    op2: false,
    args: ['visible']
  };
  options.args.push(args_arr);
  text.push(JSON.stringify(options))
  options_arr.push(options);
  args_arr = [];
}
text.push('<hr/>')
text.push(JSON.stringify(options_arr,null,2))

document.getElementById("demo").innerHTML = text.join('<br/>');
<pre id="demo"></pre>

Answer №3

It seems a bit unclear what your intention is, but perhaps cleaning up your code could offer some insights into the issue at hand.

const options_array=[];

let message = "";
for (let index = 0; index < 5; index++) {
    let choice={
      opt1:true,
      opt2:false,
      arguments:['visible',[]]
  };
  for (let j=0;j<5;j++)
   choice.arguments[1].push(index===j);
  options_array.push(choice);
}
message += JSON.stringify(options_array) ;

document.getElementById("output").innerHTML = message;

Answer №4

For incorporating the spread operator into pushing args_arr to the`options.args` array, you can use this method:

options.args.push(...args_arr);

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

Numerous objects come into view as you scroll

I found a code snippet online that animates items as they appear on scroll. However, the code only triggers animation for one item at a time. How can I modify the code to trigger the animation for all items? const observer = new IntersectionObserver(e ...

Modify content or display picture within accordion panel based on its identifier

In my view, I have a model representing a list of items. Each item has a unique ID, which is included in the H2 header tag. The details of each item are displayed in a div below the header. Initially, there is an image within the header that is set to disp ...

Enhance your web form with the Bootstrap 4 tags input feature that allows users to add tags exclusively

I'm currently utilizing Bootstrap 4 along with Bootstrap Tags Input to create a multiple category selection feature. My goal is to enable users to choose multiple items exclusively from the predefined categories listed in the predefined_list. At pres ...

Bar Chart Data Label Problem with HighCharts

My goal is to have the label positioned outside the bar stack. I attempted to achieve this using the code below, but it seems to be inconsistent in its results. dataLabels: { enabled: true, color: '#333', ...

Utilizing Ajax to Invoke Wordpress Functions from a Client's Browser

Currently working on setting up a WordPress website integrated with WooCommerce, while also developing an HTML5 app for my small online store. I am looking to utilize Ajax to call WordPress functions like search directly from my HTML5 app and receive the r ...

Unlocking Google contact pictures using Google contacts API - A step-by-step guide

Exploring the Google contacts API with Node.js I've successfully retrieved all the contacts via the Google feed API, but without images https://www.google.com/m8/feeds/photos/media/faizy04%40gmail.com/ya29.ZAFTNcQ6sEue40gFqH5h8h91k8LO8Bwvf50NUgQKKms ...

Is there a way to implement an event listener for a customized select element within a table on a webpage?

I have a table that contains columns populated from a database. I also have a custom select dropdown in one of the columns, along with an update button. I want to create an event listener for the button that captures the user's selection from the cust ...

Surprising use of template string value

After following a tutorial, I decided to create ProductScreen.js and Product.js. However, when implementing my code, I encountered some warnings. Can anyone help me identify the issue? product.js import React from 'react' import Rating from &apo ...

Ways to categorize items using JQuery based on their hierarchical structure

I am looking to organize the following HTML content: <h2>State the Issue  </h2> <h3>Provide information about your objective</h3> <h3>Share any error messages received</h3> <h2>Outline Your Attempts  ...

Connecting nodes to edges based on their unique ids in the d3.js graph library

I am encountering an issue with this code while trying to integrate it with a new JSON object called 'new_json'. Specifically, I need the links in this code to be created based on the nodes' IDs. Can anyone provide assistance with this? va ...

The extent of the modal window (AngularJS directive)

I've been experimenting with a modal window feature using Angular UI Bootstrap. Within the parent controller, I've defined the following function: $scope.open = function () { var modalInstance = $modal.open({ templateUr ...

Vue.js error: Reaching maximum call stack size due to failed data passing from parent to child component

I'm having trouble passing data from a parent component to a child component. I tried using props and returning data, but with no success. The parent component is a panel component that contains the data, while the child component is a panelBody. Thi ...

Retrieve events triggered by each element

Currently, my research centers around digital marketing and user experience. In order to gather the necessary data for this study, I must collect event logs from all components within a UI to create datasets on usability patterns. In a web interface, such ...

Transforming JSON information for Google chart data table

I am currently working on converting JSON data into a suitable format for a Google Chart visualization: var jsonData = {"Battery Voltage, (A)": {"2017-11-11T00:00:00.000Z":12.3, "2017-11-11T00:01:00.000Z":12.35, ...

Having trouble with Angular's ng-tags-input? Are you getting the error message "angular is not defined"? Let

I recently created a new Angular project using the following command: ng new "app-name" Now, I'm attempting to incorporate ngTagsInput for a tag input feature. However, every time I try to build and run my app, I encounter an error in my browser con ...

What are some tips for managing the hover effect using CSS3?

Here's a demonstration of my current setup. When you hover over the black box, a transition occurs and reveals my tooltip. However, I only want the tooltip to appear when hovering over the black box itself. Currently, the transition also triggers if y ...

Switching over to styled components from plain CSS using a ternary operator

Currently, I am in the process of converting my project from using regular CSS to styled components (https://styled-components.com/). So far, I have successfully converted all my other components except for one that I'm having trouble with. I've ...

What could be causing the "Cannot POST /api/" error to occur when attempting to submit a form?

Having issues with my basic website and struggling to find a solution. As a complete beginner in this field, I am stuck and need some guidance. Accessing http://localhost:3000/class/create works perfectly fine when running the server. However, trying to a ...

What is the most effective way to transfer information from one page to another in a PhoneGap application?

I attempted to transfer data from one HTML page to another using two different methods: function reply_click(clicked_id) { window.location = "newsList.html?Title="+clicked_id; } And I also tried: function reply_click(clicked_id) { window.l ...

Is there a way to use Jquery to determine if a parent div contains a scroll

I'm trying to find a jQuery example that checks if any parent div has a scroll bar, but I can't seem to locate a helpful one. Here is the code snippet I am working with: <div> <div class="heading"> <div class="visit ...