How can you use JavaScript to iterate through every object using a for loop?

I'm trying to determine if a button is clickable based on certain requirements, but I can't seem to get the initial function to work.

Within this object array, each object represents a button with specific requirements. For example, the "story" button requires 10 ideas, denoted by story.ideaReq = 10. To access "grana", you need to have at least 1 story, specified as grana.storyReq = 1.

The desired output of my code should be:

story ideaReq 10

which translates to:

story.name = story,
req.name+'Req' = ideaReq and
story['ideaReq'] = 10

However, what I'm currently getting is:

story ideaReq undefined

Although console.log(story.ideaReq) works perfectly fine, I need the ability to call this function for multiple objects beyond those mentioned above.

What am I overlooking?

const numbers = [
  time = {
    'name': 'time',
    'in': 0,
    'val': 0
  },
  idea = {
    'name': 'idea',
    'in': 0,
    'val': 10,
    'time': 1
  },
  story = {
    'name': 'story',
    'in': 0,
    'val': 1,
    'time': 4,
    'ideaReq': 10
  },
  grana = {
    'name': 'grana',
    'in': 0,
    'val': 1,
    'time': 1,
    'storyReq': 1
  }
];
var checkButton = (button, req) => {

  let name = button.name,
    prop = req.name + 'Req';

  console.log(name, prop, name['prop']);
}

checkButton(story, idea);

Answer №1

Make sure to access the property of button using the string stored in prop, not the name.

Replace

console.log(name, prop, name['prop']);

With

console.log(name, prop, button[prop]);

const numbers = [
  time = {
    'name': 'time',
    'in': 0,
    'val': 0
  },
  idea = {
    'name': 'idea',
    'in': 0,
    'val': 10,
    'time': 1
  },
  story = {
    'name': 'story',
    'in': 0,
    'val': 1,
    'time': 4,
    'ideaReq': 10
  },
  grana = {
    'name': 'grana',
    'in': 0,
    'val': 1,
    'time': 1,
    'storyReq': 1
  }
];


var checkButton = (button, req) => {

  let name = button.name,
    prop = req.name + 'Req';

  console.log(name, prop, button[prop]);
}

checkButton(story, idea);

Remember to declare your variables before initializing them to avoid global scope:

let time, idea, story, grana;

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

How to effectively handle asynchronous calls in Node.js using readdir and stat functions

My current project involves implementing a post method on the server side to fetch all files within a specified directory (non-recursively). Below is my code snippet. I am encountering challenges in sending back the response (res.json(pathContent);) with ...

Error with 'Access-Control-Allow-Origin' while making a request using JavaScript

In the process of creating my angular 2 application, I've implemented a module known as github-trend. Within this setup, there is a service that interacts with various functions from the module. scraper.scrapeTrendingRepos("").then(function(repos) { ...

Typescript encounters ERROR TS1128: Expecting a declaration or statement

Having trouble with a TypeScript error in my game-details.component.ts file that I've been trying to fix for a couple of hours. It's showing up at line 26, column 54 and everything seems correct to me. Interestingly, when I press CTRL + S in my ...

Utilizing ReactJS to display a new screen post-login using a form, extracting information from Express JSON

I am facing a challenge with updating the page on my SPA application after a successful login. I have successfully sent the form data to the API using a proxy, but now the API responds with a user_ID in JSON format. However, I'm struggling with making ...

Experiencing issues with undefined NextJS environment variables?

I've developed a custom script to store some fixed data onto my file system. The script is located at the following path: ./lib/createLinks.js const contentful = require('contentful') const fs = require('fs') require('d ...

Randomize the array of images in Nuxt every time the page is reloaded to display a variety of logos in the carousel

I've set up a carousel of logos, with the intention to randomize their order every time the page reloads. The challenge is that my layout only allows for 10 images to be displayed at once. While it seems like everything is functioning correctly, I&ap ...

Utilizing Vue.js to connect with a Node.js server

After setting up a basic Node.js server, the following code is running successfully: var http = require('http'); var server = http.createServer(); server.on('request', function(req, res) { res.writeHead(200, { 'content ...

Directive unable to recognize ng-pattern functionality

I am attempting to encapsulate an <input> within a directive in order to manage date validation, conversion from string to Date object, and keep the Date version in the original scope. The functionality seems to be working as intended. However, the n ...

Guide for Extracting a String in JavaScript that Includes Numerals for Color Code Alteration, Resulting in Formats like 32m+ or 31m-

Attempting to create a Firebase cloud function in JavaScript that sends email notifications for any changes in the Firebase remote config. Upon each remote config change, the string received is in the following format: { parameters: { [32m+ newer_value: ...

Encounter an Internal Server Error while using Laravel 5.4

I am encountering an issue while attempting to implement ajax search in my laravel project. I have included the controller and JavaScript code related to this problem below. Can you please take a look and let me know what may be causing the error? pu ...

Issue with PHP causing Jquery alert to trigger twice rather than once

I am currently working with jQuery and PHP. I have a button labeled "Edit" but whenever I click on it, the alert message pops up twice instead of just once. Below is my HTML code within the PHP tags: <?php $PostComment2='<div class="button1 ...

Which cleanup function will be called when I have multiple use effects with various effects in use?

I recently started diving into the world of React and have been playing around with React hooks. Imagine a scenario where I have a component with multiple useEffect hooks, each with its own cleanup function. This has raised a few questions for me: ...

How to Test React Js API Calls with Jest?

I'm currently in the process of writing test cases for my API call function, but I'm encountering difficulties as I am unable to successfully run my tests. Below is the code for the API call function and the corresponding test cases. export async ...

What is the best way to reset react-id-swiper every time an event handler is triggered in a React application?

I have incorporated the react-id-swiper module into my React project to create a dynamic image slider. By setting onClick event handlers on buttons with different id attributes, I trigger API calls that update the state and populate the ImageSlider compone ...

The full height of the image cannot be captured by html2canvas

It baffles me that html2canvas is failing to capture the full height of the div. html2canvas($container, { height: $container.height(), onrendered: function(canvas) { var data = canvas.toDataURL('image/png'); ...

Error encountered when attempting to reinitialize DataTable while iterating through multiple tables and searching within tabs

Currently, I am utilizing DataTable to display 3 separate tables with the help of tabs, along with a search function. However, every time I load the page, I encounter a reinitialization error. Here is the snippet of my code: _datatables.forEa ...

Is NodeJS Asynchronous: Has the callback been called twice?

I'm currently working with the Async module in Node.JS to manage my asynchronous calls. However, I've encountered an issue stating "Callback already called." Could someone assist me with resolving this problem? async.each(data['results&apos ...

What is causing the Unhandled Promise Rejection error when using await with Promise.all?

This is the general setup of my code: (async () => { try { const asyncTasks = [] for (let i = 0; i < 3; i++) { await new Promise((resolve, reject) => setTimeout(resolve, 1000)) for (let j = 0; j < 3; j++) { async ...

Exploring JSON response handling in jQuery using Coffeescript

When retrieving data from a JSON using an HTTP request, I am faced with a challenge. The response contains 10 objects, each comprising multiple keys. Although I can access a particular object, extracting the key proves to be difficult. The following code ...

Having trouble removing a row from Mysql database using Node.js

Recently, I developed a pet shop web application using nodeJS and MySql. Everything was working smoothly until I encountered an issue with deleting pets by their pet_id. Upon attempting to delete using pet_id 'pa04', I received the following erro ...