Generating variable names dynamically in JavaScript

To prevent a javascript heap issue, I implement the usage of multiple arrays including 'family1', 'family2','family3' and 'dogs1', 'dogs2', 'dogs3'. For instance, you can use 'family1 and dogs1', or 'family132 and dogs132' to form a new array named 'results'.

How should I correctly pass the "id" value?

let  id = 'value here'
this.family + id
this.dogs + id

Currently, my 'str' goes into the new array as: t-h-i-s-.-f-a-m-i-l-y-1

for (let i = 0; i < 20; i++) {

  const id = 1;
  let str = 'this.family'+id;   // ?
  let str = 'this.dogs'+id;   // ?

  console.log(str);

  const result = {
      familyType: str[i],       // output: t-h-i-s-.-f-a-m-i-l-y-1
      protocol: this.dogs1[i],  // expecting original behavior
  };

  results.push(result);

}

}

Answer №1

Searching for the following:

let str = this['family'+identifier]; 

However, relying on this pattern is not recommended. Avoid naming variables with sequential numbers. Instead, consider using 2D arrays (arrays containing arrays as elements), such as this.pet[identifier][index]. If you encounter a "javascript heap problem", it may be caused by different code.

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

The body parser is designed to efficiently parse and handle both gzip and json formatted HTTP POST request bodies

I've set up an API endpoint to manage http POST requests from a client. At the moment, I'm using Express framework and bodyParser to handle request bodies. What I need help with is configuring body-parser to effectively handle cases where request ...

Discover the best practices for utilizing the npm commands.test function

Looking to create a function that can return the output from running npm test. (this function can be called as npm.commands.test(packages, callback) here) Attempted to use it in this way: var npm = require("npm"); npm.load('', function(err, np ...

Effective Ways to Transfer Input Parameters to Karate File using npm

I am working on a test script that runs a series of queries. In order to execute the file, I need specific inputs such as URL and authorization header, which will vary depending on the environment. How can I prompt the user for these inputs in the command ...

A Guide to Effectively Extracting Data from Second Level JSON Arrays with

Hi, I'm having difficulty fetching the two attributes under CategoryImage in the second level of the JSON array parsing. Can someone help me with this? Thank you. <script> $(document).ready(function() { var cat=""; ...

Utilize JavaScript to append elements to an array in each loop iteration, gradually building a single, unified

I find myself in a situation where an async request is sending data to a child react component. Upon logging the "data" in the component, I receive multiple arrays sequentially. Ideally, I would prefer not to rewrite the request in the parent component and ...

Retrieve the total count of rows present in a specific table

Is there a way to accurately determine the number of rows in a table? I've attempted multiple methods (all unsuccessful) and this is my latest attempt: var _tableOfInterestsCount = wait.Until(x => x.FindElements(By.XPath("//*[@id='gridBody ...

Experiencing difficulties with a callback function while making a jQuery getJSON request via AJAX

Within my utility .js file, there is a method that fetches data using Ajax. The challenge I am facing is that this method does not have prior knowledge of the caller. After the Ajax call completes asynchronously, it needs to send an object back to the cal ...

Leverage Node.js modules to reassign variable values

My simplified JavaScript module simulates an eye pose. var pose = {}; var eye = {}; var left = {}; left.pitchPos = 37; left.yawPos = 47; exports.init = function () { eye.left = left; pose.eye = eye; return this; }; exports.eye = function (e ...

Steps for sending a request to the root resource

I've encountered a problem that stems from my limited knowledge of Express. Despite creating a project with Express, I'm unable to make calls to the root, only to the routes. I suspect the issue lies in my usage of app.use(...). app.js var inde ...

Resolving a Tricky Challenge with jQuery's

I am facing an issue with a function that animates images through crossfading. This function is responsible for rotating banners on a website. By calling the function as animateSlideshow("play"), it starts animating and sets up a timeout. On the other hand ...

Utilizing Promises in the apply function

I am currently working on a project in Node.js that utilizes bluebird for promise handling, as well as ES6 native promises. In both projects, I have a chain where I make a database query structured like this: some_function(/*...*/) .then(function () ...

Tips for responding to and disabling a specific button in Vuetify.js after clicking the follow or unfollow button

I have a situation where I need to implement a functionality for a series of buttons with follow and unfollow statuses. When a user clicks on any button, I want the status to change after a brief delay and deactivation, followed by reactivation. For instan ...

No reply received on the web browser

I have written a code that is intended to read a JSON file and display it in the browser. The code is functioning correctly as it prints the data to the console, but for some reason, the data is not displaying on the browser. app.post("/uploadfile&q ...

The canvas is unable to render the image from the sprite sheet

I successfully drew an image representing the player, but now I'm encountering difficulties in drawing an enemy character. Despite adding alerts indicating that the program is executing the draw enemy function, the enemy character still doesn't a ...

How to display (fade in a portion of an image) using .SVG

I have the following code in my DOM: <div class="icon-animated"><img src="icon_non_active.svg" id="icon_non_active"></div> There are two icons (.svg) available: icon_non_active & icon_active Can I animate the transformation from i ...

Encountering issues with CSS Modules in Next.JS app while using app/about/layout.tsx

Currently, I am delving into the world of Next.js and encountering some challenges with locally scoped CSS modules. In my project, I have an about directory which contains a layout component. Strangely, the styles applied to the layout component are not b ...

Storing information in a MongoDB database using Node.js

Context: Looking to insert data into a MongoDB database using Node.js Problem Statement: Attempting to insert data into the MongoDB database but encountering an error. Unable to locate the issue. Present Output: Reference Error Attach Code: filter.js ...

Using Jquery to delete the parent element containing text that does not match

I need to search for text in a table cell that matches the text in an h1 heading and then eliminate all other table rows containing text that does not match. The code snippet provided only works if there is one .tablerow with a .tablecell, so I am looking ...

Displaying a timer output in an HTML div every second using PHP

I created a custom PHP countdown timer that displays the remaining time in hours, minutes, and seconds (specifically 3 hours) - named countdown.php. The timer output is displayed within a <div> tag on another page called index.html. Now, I am lookin ...

In search of a straightforward programming logic resolution

Currently, I am working on a project using CakePHP 2.x, and although my question is not related to syntax at the moment, I require assistance with a particular issue: Within my database, there exists a table called messages which contains a field named mo ...