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

Incorporating map() with data passed down as props from App.js into child components

I have React version 18.2 and I want the child component in App.js to receive data and utilize the map() function. Although the child component successfully receives the data, it is encountering an issue when trying to use map(). An error message is disp ...

Is it possible for jQuery UI Tabs to load entire new HTML pages?

In my index.html file, I have set up 3 different tabs. Using the jQuery UI function tabs(), I am attempting to load an HTML page via Ajax. Each HTML page includes the jQuery library and contains the following code: <link type="text/css" href="css/redmo ...

How can I efficiently add multiple items to an array and store them in async storage using React Native?

I am trying to store multiple elements in local storage using React Native. I found some helpful documentation on how to do this here. Could someone guide me on the correct way to achieve this? Here's a snippet of my code: My current approach const ...

What is the best way to implement Axios for data fetching in Gatsby's useStaticQuery function?

One way to fetch data in Gatsby is by using GraphQL, like in the following example: import { graphql, useStaticQuery } from "gatsby" const IndexPage = () => { const gatsbyRepoData = useStaticQuery(graphql` { github { repo ...

Issue experienced with Vue2 where utilizing a computed property to filter a nested v-for structure

I have a unique HTML challenge that requires me to iterate through an unconventional data setup. The information is retrieved in two separate parts from Firebase: one for categories and another for businesses. The structure of the data is as follows: Busi ...

Navigating a local and server environment with relative paths in a web server's multiple sites

My ASP.NET website is published to a web server with multiple sites, such as www.example.com/SiteA or www.example.com/SiteB. Before publishing, I test the site locally at localhost:12345. When referencing an image path like /Images/exampleImage.gif, it wo ...

Enhance Canvas when React State Changes

I am currently working on integrating a canvas into my React project. The main goal is to overlay styled text (with custom font color, style, and size) on an image. I've set up a basic form to input the styling attributes and the desired text. Whenev ...

Guide to using Ajax to send a form and receive text in response

Check out my code on Fiddle: $("form.signupform").submit(function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr("action"); var form = $(this); // Added this line for reference $.post(url, data, function(data) { $(for ...

"The changes made to the list are not being accurately displayed by Angular's ng

I am working on a directive that injects dynamic templates during ng-repeat. While I can successfully add items to the list, they do not appear in the view for some reason. It seems like I am missing a crucial piece to make it work correctly. You can find ...

Using jQuery to delay hiding for 2 seconds

Hey there! I'm facing an issue with my code. The function is supposed to make #aboutPopOut slide to the left, and then after a 2-second delay, fade out the fadescreen by hiding it. The sliding part works fine, but the waiting and hiding do not seem to ...

`The resurgence of CERT_FindUserCertByUsage function in JavaScript`

I am currently grappling with unraveling the connection between C++ dlls and JavaScript. There is a snippet of js code that reads: cert = CERT_FindUserCertByUsage(certDB, certName.nickname,certUsageEmailSigner, true, null); where the variable cert is ini ...

What could be the reason for the component bindings being undefined within the controller?

I'm currently working on a basic angular component. I have set up a parameter as a binding and managed to display its value on the screen successfully. The parameter displays correctly, but when I try to access it within the controller, it shows undef ...

What is the best way to modify a constant array in Angular?

Hello team, I'm fresh to working with angular and I have a TypeScript file that contains a list of heroes: export const HEROES: Hero[] = [ { id: 11, name: 'Dr Nice' }, { id: 12, name: 'Narco' }, { id: 13, name: 'Bombas ...

Why does this code snippet throw an error if let is not hoisted or in the temporal dead zone? It could have simply used the global reference instead

var b = 6; { console.log(b) let b = 55 } When running this code snippet, I encounter the following error message: ReferenceError: Cannot access 'b' before initialization Why is the console.log(b) not displaying 6 as expected? ...

Do not open iframe links in a new window

Is it possible to manipulate the iframe so that links open inside the iframe window? I want the links clicked within the iframe to stay within the same window instead of opening in a new one. However, I have too many links to individually edit their code ...

Monitoring changes in an array of objects using AngularJS's $watch function

Exploring the world of AngularJS, I'm on a quest to solve a challenging issue efficiently. Imagine having an array of objects like this: var list = [ {listprice: 100, salesprice:100, discount:0}, {listprice: 200, salesprice:200, discount:0}, {listpr ...

What is the proper syntax for Angular 2 form element attributes?

As I was browsing through this insightful article, I came across the following snippets: <input type="search" [formControl]="seachControl"> and <input type="text" formControlName="street"> This made me ponder on the correct syntax for ...

The "require" keyword cannot be used in a Node-RED Function node

When working with a Node-RED Function Node, the first line I include is: var moment = require('moment-timezone'); I'm attempting to create a timezone accurate date/time stamp for sensor data. However, when this node runs, I encounter the fo ...

Ways to manually trigger a reevaluation of Vuelidate validation

Is there a way to trigger Vuelidate to re-check a validation? For example, I have a form field where users can input the name of a remote directory. There is a Vuelidate validation in place that communicates with the server to verify if the directory exis ...

What is the process for uploading an image using fetch?

After just starting to learn react, I decided to create a gallery App. However, I am facing an issue when trying to post pictures to the API. Whenever I click on the ADD button, nothing happens except for an error 500 being logged in the console. Below is ...