JavaScript - Iterating over an object using a loop

I'm attempting to generate dynamic buttons based on an object:

var buttonsMenu = {
  "A":{
    A1: 97,
    A2: 85, 
    A3: 65,
    A4: 70,
    A5: 40
  },
  "B":{
    B1: 97,
    B2: 85, 
    B3: 65,
    B4: 70,
    B5: 40
  }
};

var categoryButton = "A";//or B

// create a button for each category
for(property in buttonsMenu.categoryButton){// facing challenges here
  var newEl = document.createElement('button');
  newEl.innerText = property;
  newEl.setAttribute('data-name', property);
  buttons.appendChild(newEl);

This approach works with the string value A or B in the loop:

 for(property in buttonsMenu.A)

I expected the same behavior by using a variable, but it doesn't work.:

var categoryButton = "A";
for(property in buttonsMenu.categoryButton){

What am I doing incorrectly here? Appreciate your help!

Answer №1

make sure to utilize buttonsMenu[categoryButton]

const buttonsMenu = {
  "A": {
    A1: 97,
    A2: 85,
    A3: 65,
    A4: 70,
    A5: 40
  },
  "B": {
    B1: 97,
    B2: 85,
    B3: 65,
    B4: 70,
    B5: 40
  }
};

let categoryButton = "A" //or B

// generate a button for each category
for (let property in buttonsMenu[categoryButton]) {
  let newEl = document.createElement('button')
  newEl.innerText = property
  newEl.setAttribute('data-name', property)
  document.body.appendChild(newEl)
}

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

Javascript - Error encountered when utilizing a for loop to insert a new column into an array

I have been utilizing an API to fetch data on various stocks, and I am attempting to include a column named "symbol" with the query values using the function insertColumn. However, I am encountering an error message that says (node:15732) UnhandledPromiseR ...

Issue with converting string to Date object using Safari browser

I need to generate a JavaScript date object from a specific string format. String format: yyyy,mm,dd Here is my code snippet: var oDate = new Date('2013,10,07'); console.log(oDate); While Chrome, IE, and FF display the correct date, Safari s ...

Empower your presentations with slick cloning technology

I am facing an issue with my slider that I cannot seem to resolve. Currently, I am using slick to display 3 slides, but only the center one shows all the content. To achieve a continuous infinite slider effect where all slides appear in the center, I need ...

Emphasize any word starting with an @ symbol to highlight its importance

My goal is to enhance the appearance of words that begin with an "@" symbol by making them bold. For example, transforming the sentence: '@xyzharris has a cat @zynPeter' into: '@xyzHarris has a cat @zynPeter' ...

Enhancing the parentheses operator for Set() and Get() operations

The task at hand is: For the MyString object, you are required to overload the following operators: 1) The parenthesis operator should be overloaded to replace the Set and Get functions from your previous assignment. It's important to note that both ...

Verify the final element in the array

I have an array of strings, and I need to compare the i element with the i + 1 element for any similarities, excluding the last element as it has already been checked by the previous one. String[] somearr = new {"first, second"}; arr[i] && arr[i+ ...

Is there a way for me to extract and showcase the initial 10 items bearing a particular class name from a different html document on my homepage?

I am looking to extract a list of movies from an HTML file titled "movies.html". The structure of the file is as follows: <div class="movie">Content 1</div> <div class="movie">Content 2</div> <div class=" ...

Is there a way to send a promise resolve or reject from a function code within router.post() in Express?

Below is my code in express (node.js) router.post('/example.json', function (req, res) { // getFileInfo is a function to return an array return getFileInfo(req.body.fileList).then((array) => { axios({ method: 'post', ...

Breaking down the GET string

I am facing a challenge in splitting my GET string into an array. The structure of the string is as follows: ident[0]=<IDENT_0>&value[0]=<VALUE_0>&version[0]=<VERSION_0>&....&ident[N]=<IDENT_N>&value[N]=<VALU ...

What is the best way for Flask to host the React public files?

When working with React, I created a folder called ./public/assets, and placed an image inside it. Running npm start worked perfectly fine for me. However, after running npm run build in React, I ended up with a ./build folder. To solve this issue, I moved ...

Ways to execute a function when clicking on a date using HTML 5 datepicker input type

How can I call a function in angular js when a date is selected from an html5 date-time picker using a mouse click? I need help with this. Here is the HTML code: <div class="col-lg-4"> <input class="form-control" type="datetime" date-time auto ...

image source that changes dynamically with a placeholder image

Currently, I am facing a certain issue. Unfortunately, I cannot provide a plunkr example as the image is sourced from a protected site and there are no open URLs available that constantly serve changing images. Additionally, I am unable to use a local anim ...

Upon exiting the page, save the initial array in storage. However, the back button will load the last committed array

Currently, I have a feature on my website where users can filter articles based on their category. When the user selects the "ideas" filter, it creates a new array called "ideasFiltered" and stores it in the "filteredArticles" state. This works perfectly w ...

Include the <script> tag in the HTML code for an iframe without running it

Currently, I am working on an HTML code that involves memory for an Iframe. Interestingly, whenever I use the append function, it not only executes the code but also carries out its intended task. html = $(parser.parseFromString($("#EHtml").val(), "text/h ...

Modifying the order of Vuetify CSS in webpack build process

While developing a web app using Vue (3.1.3) and Vuetify (1.3.8), everything appeared to be working fine initially. However, when I proceeded with the production build, I noticed that Vue was somehow changing the order of CSS. The issue specifically revol ...

Clicking on a checkbox within an HTML table that incorporates handlebar and Express.js

My situation involves a HTML table within a form that is being populated with Handlebars. I need to be able to select certain rows in the table using checkboxes, and upon form submission through a POST request in an Express.js framework, I require the JSON ...

Arranging Images, Buttons, and Text Vertically in React with CSS

https://i.sstatic.net/0WaeI.png In my current application, whenever the button is clicked, a random image is generated but it results in everything appearing bunched up. I would like the images, which are of different sizes, to be displayed with the dog&a ...

Switch up the Position of a Frame with jQuery

I'm attempting to cycle through an array of URLs in order to designate them as locations for a frame. The current setup I have can be found on this fiddle: var l = ['0', '1', '2', '3', '4', '5&ap ...

Utilizing JavaScript or jQuery in MVC4 to showcase information for the primary record

I'm currently working on constructing a page that displays a list of users. My aim is to have a "Details" link in each row that, when clicked, will render a partial view on the same page without having to reload it using either javascript or jQuery. D ...

Accepts numerical values and a single comma

Is there a way to restrict an input field to accept only numbers and exactly one comma? Here's the approach I've been using: $("#my-field").on("keyup", checkKey); function checkKey() { this.value = this.value.replace(/[^0-9,]/g, ""); } ...