How to Identify an Array in JavaScript using a String

I'm experiencing some challenges with retrieving a pre-declared array based on user input. This task is designed to help me grasp how to capture user feedback using an HTML drop-down and then return a value using a script.

What I aim for in the second part of the script is to retrieve the array that corresponds to the string selected by the user.

/* The current method successfully fetches the required array, but it involves placing them inside an object and returning them based on the key,
something I'd prefer to avoid. */

const obj = { att: [1, 1, 1, 1], btt: [2, 2, 2, 2], ctt: [3, 3, 3, 3], dtt: [4, 4, 4, 4] };
function getOption() {
  let choice = document.getElementById("mySelect").value;
  function pick(name) {
    return obj[String(name)];
  }
  document.getElementById("demo").innerHTML = pick(choice);
// For drop-down choice "att", output will be "[1,1,1,1]".
}

/* In this section, even though the arrays are named One and Two respectively, and I am returning a string that represents either 
"One" or "Two", JavaScript doesn't seem to recognize these as array names and simply returns the strings themselves. */

const One = ['a','a'];
const Two = ['b','b'];
function getSecondOption() {
  let choice = document.getElementById("mySelectZwei").value;
  function pick(name) {
    return String(name);
  }
  document.getElementById("demoZwei").innerHTML = pick(choice);
// For drop-down choice "One", output will be "One".
}

I have attempted to remove the use of String() in the second segment, but without any impact. The Array.isArray() method also failed to produce results, indicating that the editor does not establish a linkage between the array names and the strings.

I would greatly appreciate any guidance on what areas to explore further or suggestions for potential solutions.

Thank you very much!

Answer №1

If my memory serves me right, you have the option to utilize var rather than const. This way, variables won't be confined and linked to the global object window, making them accessible through window[name].

Give this a shot:

var One = ['a','a'];
var Two = ['b','b'];
function getSecondOption() {
  let choice = document.getElementById("mySelectZwei").value;
  function pick(name) {
    return window[name];
  }
  document.getElementById("demoZwei").innerHTML = pick(choice);
}

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

Utilizing Custom HTTP Headers in Angular 2 to Enhance Request Handling

Within my Angular 2 project, I am implementing the use of Http (@angular/http) to communicate with my API. In order for these requests to be successful, specific headers, including a JWT header, must be included in each API request. My goal is to have an ...

Distinguishing Between Angular and Ajax When Making Requests to a NodeJS Server

Trying to establish communication between an Angular client and a NodeJS server. Previous method using JQuery $.ajax({ url: "/list", type: "POST", contentType: "application/json", dataType: "json", success: function(data) { console.log("Data ...

Array in Javascript reset to null after its second iteration

''' const users = [] const addUser = ({ id, username, room }) => { // Clean the data username = username.trim().toLowerCase() room = room.trim().toLowerCase() // Validate the data if (!username || !room) { r ...

Associate the URL with the object to retrieve the corresponding object

https://i.sstatic.net/cj5N4.png When iterating through this array, I currently loop through it in the following manner: {props.choosenMovie.characters.map((characters) => ( <p>{characters}</p> /* This displays the URL of course */ ))} ...

Tips for setting up a popup menu when clicking a button on a webpage

I am currently working on developing a popup menu with a greyed-out background that appears when the user clicks on a button in React. My code implementation is as follows: // The ifButtonClicked function is called when another button is clicked // Some ...

Tips for adjusting the position of an object when resizing the window

The problem at hand is as follows: Upon refreshing the page, my object is initially positioned correctly. However, resizing the window causes the object to resize and reposition correctly. But, if I refresh the page after resizing the window, the object i ...

Every time Chrome on Android returns a keyCode of 229

Here is a snippet of code that I am having trouble with: ... @HostListener('keydown', ['$event']) onKeyDown(evt: KeyboardEvent) { console.log('KeyCode : ' + evt.keyCode); console.log('Which : ' + evt.which); ...

What are some techniques for transforming text into JSON format?

Beginner inquiry: I'm struggling with manipulating text using JavaScript. Here is the text I want to transform: "5555 55:55: John: New York 6666 66:66: Jack: Los Angeles" My desired output after manipulation: [{ name:"John", address:"New York", n ...

Interactive inclusion of choice options generated through JSON

My task involves dynamically creating table rows with select values from a JSON array. While I can successfully add a row, the other dropdown lists are not functioning properly in the code below. When trying to concatenate the ID of the select with a fun ...

How do I choose and click on a JavaScript link using Watir-Webdriver?

For my mobile webapp, I am attempting to create a test using cucumber+watir-webdriver. However, I am encountering difficulty when trying to select a specific link on a splash message. The link I need to choose is <a class="btn" href="#">Close button ...

Customizing the appearance of charts in AngularJS using the Chart.js

I just started experimenting with AngularJS and recently created a horizontal bar chart using Chart.js and HTML. My next step is to make the chart dynamically appear on the page with the help of AngularJS. Can someone please provide some guidance on how I ...

Increasing the upward motion of the matrix raining HTML canvas animation

Recently, I've been experimenting with the Matrix raining canvas animation here and I was intrigued by the idea of making it rain upwards instead of downwards. However, my attempts to achieve this using the rotate() method resulted in skewing and stre ...

What is the process for changing the output paper size to A4 in React Native (expo android)?

Using React Native to develop an Android app for billing purposes, I encountered an issue with the output paper size being 216mmX279mm instead of the standard PDF size of 210mmX297mm. Utilizing expo-print and printToFileAsync from expo, I aim to achieve a ...

The functionality of the "Slots" prop has no impact when used on the material-ui Slider component

Trying to understand the purpose of the "slots" prop in relation to customizing how inner components like track and thumb are rendered within the Slider component. A basic example of rendering a Slider component is shown below const marks = [ { value: 0 ...

Stop automatic page refresh after submitting a jQuery post request

I've tried various solutions, but unfortunately, neither e.preventDefault() nor return false seem to be working for me. When I use prevent default ajax doesn't make post request. Even using $.post doesn't work as expected. Furthermore, addin ...

Troubleshooting: Issues with AngularJS $route.reload() functionality

I have an angular app and I'm attempting to refresh the page. I've tried using $route.reload() as recommended in multiple posts, but I can't seem to get it to work (Chrome is showing me an error). Here's my controller: var app = angula ...

Change a CSV document into JSON format by transforming one of the fields into an array

Currently, I am in the process of compiling some data into a csv file with the goal of later converting it into a json object. Here is a glimpse of what a few rows of my data look like (the first row represents the header with column titles) Scientifi ...

Utilizing Angular Schema Form to Populate Form Fields with JSON Data

As a hardware engineer venturing into the realm of creating an in-house software tool, I initially thought it would be a straightforward process. However, I've encountered a plethora of unknowns hindering my progress. My goal is to develop an interna ...

Background Services in the Moment

Currently in the process of developing a mobile application with the Ionic framework that utilizes Laravel 4 REST API for CRUD operations on a MySQL database. As per the requirements of the app, it needs to constantly communicate with the backend service t ...

Using Ajax to transmit a model from a list traversed by a foreach loop to a controller

When sending a list of a model back to the controller from a view, I want it to happen only when the input has been checked. Although using AJAX makes it work, the page refreshes and the data is not caught, but it shows up in the URL. For example: https:/ ...