Designating a variable as an array target in Javascript (how does it affect mutability?)

I am struggling with managing 5 arrays in JavaScript based on a variable called "x". I'm having difficulty understanding how to properly use and update these variables in my code. Here is an overview of what I'm trying to achieve...

//Arrays to hold IDs of nodes
nodeOne = [];
nodeTwo = [];
nodeThree = [];
nodeFour = [];
nodeFive = [];

//Mapping buttons to node arrays
var nodesButtonToNode = {pn_btn_1:"nodeOne", pn_btn_2:"nodeTwo", pn_btn_3:"nodeThree", pn_btn_4:"nodeFour", pn_btn_5:"nodeFive"};

x = "pn_btn_1"; 

nodesButtonToNode.x.push("I am supposed to go into nodeOne")

In essence, the value of "x" determines which array should be filled according to the key in nodesButtonToNode. For instance, if x = “pn_btn_1”, then data should be added to the nodeOne array. However, I keep encountering undefined errors and can't pinpoint where I'm making a mistake.

Any advice or insights would be greatly appreciated. Thank you!

Answer №1

To efficiently store and access data, consider using an object where the array names serve as keys allowing you to retrieve values using bracket notation such as obj[var]:

//Assigning IDs to node arrays
const nodes = {
  nodeOne: [],
  nodeTwo: [],
  nodeThree: [],
  nodeFour: [],
  nodeFive: []
};

var nodesButtonToNode = {
  pn_btn_1: "nodeOne",
  pn_btn_2: "nodeTwo",
  pn_btn_3: "nodeThree",
  pn_btn_4: "nodeFour",
  pn_btn_5: "nodeFive"
};

x = "pn_btn_1";

nodes[nodesButtonToNode[x]].push("I am supposed to go into nodeOne");

console.log(nodes);

Answer №2

Ensure that your nodesButtonToNode function references the actual arrays, not just their names.

var nodesButtonToNode = {
    pn_btn_1: nodeOne,
    pn_btn_2: nodeTwo,
    pn_btn_3: nodeThree,
    pn_btn_4: nodeFour,
    pn_btn_5: nodeFive
};

This approach allows for direct updates to the arrays.

It's important to note that x should be assigned the value of pn_btn_1 in your mapping.

//Arrays containing IDs of each node
nodeOne = [];
nodeTwo = [];
nodeThree = [];
nodeFour = [];
nodeFive = [];

var nodesButtonToNode = {
    pn_btn_1: nodeOne,
    pn_btn_2: nodeTwo,
    pn_btn_3: nodeThree,
    pn_btn_4: nodeFour,
    pn_btn_5: nodeFive
};

x = "pn_btn_1"; 

nodesButtonToNode[x].push("Inserting content into nodeOne");

console.log(JSON.stringify(nodeOne));

Answer №3

There are a few mistakes in the way you've written your code snippet. Here's an example of how it should look:

const firstNode = [];
const secondNode = [];
const thirdNode = [];
const fourthNode = [];
const fifthNode = [];

const nodeButtonMapping = {
  btn_1: firstNode,
  btn_2: secondNode,
  btn_3: thirdNode,
  btn_4: fourthNode,
  btn_5: fifthNode
};

const key = "btn_1"; 

nodeButtonMapping[key].push("This should be added to firstNode");

console.log(nodeButtonMapping);

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

Securing Your Vue.js Application Against Copy and Paste Issues

For the purpose of making it challenging for those who steal content, I want to prevent the copy-paste function on rendered texts within vue.js components. Take a look at this template example: <template> <div id="my-precious-content"> ...

JavaScript - Placing Image Caption and Details within a Box

<div id="CollectionALL"> <div id="collection1" class="col"> <img id="Img1" class="imageCS"/> <H1 id="Title1"></H1> ...

Something is amiss with the PHP email validation functionality

I have been facing issues with the functionality of my form that uses radio buttons to display textboxes. I implemented a PHP script for email validation and redirection upon completion, but it doesn't seem to be functioning correctly. The error messa ...

Diagnosing the character count error in an ASP.NET text box

I encountered a persistent error 0x800a1391 - JavaScript runtime error: 'txtMessage' is undefined while attempting to calculate the character count of a text box. <script type="text/javascript"> function textCounter(field, countfield, ...

Avoid using @2x images on iPad 3 when rendering in HTML5 Canvas

Recently, I developed a game using the HTML5 canvas. However, it seems that the performance of this game on my iPad 3 is not as good as expected. I am speculating that the retina display of the iPad might be the cause of this issue. Is there a possible sol ...

Tips on confirming the completion of my form when the next button is pressed

I am working on a multi-step form with a jQuery script to split the forms. The first form has only one button - the next button, which takes the client to the next form. However, when I click on the next button in the first form, it moves to the next form ...

"Can you explain the process by which React grabs the props using the code `const props = this.props

I recently came across an interesting article authored by Dan. The example provided in the article caught my attention: class ProfilePage extends React.Component { showMessage = (user) => { alert('Followed ' + user); }; handleClick ...

Dynamically including and deleting classes upon clicking using React

Looking for a solution to handle a list of links. The goal is to add a class called "is-active" when a link is clicked, while also removing any existing "is-active" classes from other links. Only one link should have the "is-active" class at a time. This ...

Navigating through the world of WebSQL data entry

I've encountered a challenge while utilizing WebSQL for my Chrome Extension. This is my first experience with it, so I decided to refer to this tutorial and modify it to suit my requirements: http://www.html5rocks.com/en/tutorials/webdatabase/todo/ B ...

Aligning text to the right in Bootstrap 5 input fields

I'm trying to align the values of my inputs to the right. Any suggestions on how to achieve this? Here's a visual representation of what I'm looking for. This is the snippet from my code: <td style="text-align:center; vertical-alig ...

Is there a way to display a multidimensional array according to the key?

I have an array that contains multiple dimensions as shown below: $adminoptions = array(array("hello","replies",0),array("goodbye","replies",1),array("hola","flagged",0)); What I want to achieve is to extract 'goodbye', 'replies' and ...

Turn off the annoying right-click context menu in Firefox

I'm currently working on an HTML 5 game that requires the player to use right click for control. To disable the right click context menu, I have used the following code: <body oncontextmenu="return(false);"> However, I discovered that in Fire ...

Is there a reason why angularJS doesn't provide the exact error location directly, opting instead to just offer a link to their website that provides a generic explanation?

Why does AngularJS not provide the specific error location directly, such as which file the error is in, instead of just giving a link to their website with a generic explanation? This makes debugging very challenging! Whenever there is an error, it becom ...

Is there a variation in IE6 versions depending on the operating system used?

It's puzzling to me that customers are reporting bugs on W2K machines in IE6, yet when I test locally on a WinXP System, everything appears normal. Could it be possible that there are differences in JavaScript Execution between the two systems? I do ...

How can I utilize regex to change the background color of a specific character in a react/typescript application?

One of my components contains mapped data, and I've been tasked with changing the background color of specific characters, namely "Miss", "Mrs", and "Ms". I've attempted to use regex, but I keep encountering an error that the object is possibly n ...

Utilizing Jquery for efficient event delegation across various elements and events

I need to ask my question quickly because my English is not very good. Is it possible for me to use delegate in this way or is there a similar alternative? $( 'body ').delegate({ 'input[type=text]': { 'change' ...

Bubblesort algorithm is effective for sorting a 2D array in only one direction

While I've seen posts about sorting a 2D array in C using bubblesort, I'm encountering a strange issue. Ascending sorting is causing half of each "word" to be printed, while descending sorting works perfectly (even though the algorithms are simil ...

Tips for ensuring a div stays centered while resizing the window

When I resize the window, the div tab on the right side of the screen moves to the bottom right. How can I make it stay in the middle regardless of screen size? I've tried using margin-left:auto and margin-right:auto but it didn't work. Changing ...

Divide a NumPy array into sections

Within my array x, consisting of 30 elements, I aim to divide it into chunks of 8 samples each in two unique ways: Firstly, I seek to separate the array without any overlap, resulting in 3 arrays of length 8 and a final array with only 6 elements due to m ...

Transferring HTML variables to an Angular Component

I am currently trying to transfer the information inputted into a text-box field on my webpage to variables within the component file. These variables will then be utilized in the service file, which includes a function connected to the POST request I exec ...