Using the variable (parameter) as a property in JavaScript

This function I'm creating will calculate the quantity of food data.

const countFood = (foodType) => {
  let foodNeeded = 0;

  if (animal.food.type === foodType) {
    foodNeeded += +animal.food.amount;
  };

  const food = foodType;

  if (foodNeeded > (pavilion.food[food] - 1)) return true;

  countFood(foodType);
}

countFood('meat');

This piece of code is used within a for loop.

I want to utilize this argument to access it in the form of pavilion.food.meat

Answer №1

To retrieve a property of an object, you can use the bracket notation method.

For example:

const park = {
  attraction: {
    rollercoaster: 2
  }
}

function getAttraction(attractionType) {
  const ride = park.attraction[attractionType]
  
  console.log(ride)
  
  return ride
}

getAttraction('rollercoaster');

Answer №2

Assuming you possess:

{
  garden: {
    fruits: {
      apples: {...}
    }
  }
}

You will be able to access the internal object using garden.fruits['apples'].

In a broader sense, garden.fruits[fruitName].

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

Guide to transforming text fields into input elements in Angular 4

Explore My HTML Seeking to incorporate a one-click edit feature that converts all fields into input boxes easily. Check out my HTML snippet below: <div class="col-md-3"> <div class="add-details"> <span>LemonCandy, ...

Unable to modify the title property of a link

Currently, I am in the process of transforming my website to support multiple languages. To achieve this, I have implemented a function using jQuery that dynamically changes text when a language button is clicked. While this method has been successful for ...

When refreshing data, duplicate the d3 graph

When I try to update my d3 graph after selecting a site from the dropdown menu, a new graph is generated and I can't figure out how to remove the old one. https://i.sstatic.net/R5BNE.png Below is the code within the script tags: <script> imp ...

What is the best way for me to utilize top-level await in my

I'm in the process of developing a react app and I need to make a function call like this: if (typeof window !== 'undefined') { var token = (await getItem('secure_token')); } if (typeof window !== 'undefined') { var user_ ...

How can we avoid page flickering and stuttering while scrolling using the ScrollTo script?

Currently, I am utilizing Ariel Flesler's ScrollTo script which can be found on this page. There are two links located at the bottom of the page that when clicked, will scroll to the top of the page. One of the links also triggers a contact form to op ...

Do you need to finish the Subject when implementing the takeUntil approach to unsubscribing from Observables?

In order to prevent memory leaks in my Angular application, I make sure to unsubscribe from Observables using the following established pattern: unsubscribe = new Subject(); ngOnInit() { this.myService.getStuff() .pipe(takeUntil(this.unsubscr ...

What is the method for importing a JavaScript file into my TypeScript file?

Recently, I've encountered an issue while working with Typescript and angular 2. I have built an EncryptionService that looks like this: import {Injectable} from 'angular2/core'; import './lib/hmac256-enc64'; @Injectable() ...

Efficiently align a Modal in React without the need to rewrite any code

In my application, I have a class called InventoryView that is responsible for displaying a list of stock items. The class is structured as follows: class InventoryView extends Component { ... render() { ... { consumableItemsArray.map((ro ...

Leverage vuejs' this.$refs to work with multiple elements at once

I am working with 4 select elements: <div class="form-row"> <div class="form-group col-3"> <label for="stateSelect">Status</label> <select v-model ...

datetime-local format changing after selection

In an ionic application running on an android system, there is a issue with the formatting of <input type='datetime-local'> inputs. After a user selects a date, the Start input is formatted differently than the Ende input. Attempts to use t ...

Utilizing a shared service for multiple JSON datasets in AngularJS: A beginner's guide

After successfully creating a service that retrieves data from a local JSON file and uses it in a controller to display it in the browser, everything seems to be working well. Here is the code snippet: JavaScript Code: var myApp = angular.module("myApp", ...

Accessing Jquery's $.get function is currently not possible

I am experiencing difficulty fetching the contents of a json.txt file located in the same directory as this markup. Additionally, there are no errors appearing in Firebug. <!DOCTYPE html> <html> <head> <script type="text/ja ...

Node.js equivalent of the `Pattern.compile` function

This Java/Android code works perfectly to extract all text between <tag> and </tag> What is the equivalent of this Java code in Node.js/Javascript? private static final Pattern TAG_REGEX = Pattern.compile("<tag>(.+?)</tag>"); pri ...

Repeating a post retrieved from a query in the function.php file

Looking to implement an AJAX post filter based on category? Check out this resource I found: The challenge I'm facing is customizing the post output from function.php. Currently, it looks like this: echo '<h2>' . $query->post-> ...

What is the maximum amount of information that can be stored in a data attribute within the DOM?

Occasionally, I find myself wanting to include a substantial amount of data on the webpage in order to minimize additional AJAX calls for dynamic content. However, I am concerned about potential performance implications. Is there a penalty I should be aw ...

Newbie's Guide to Function Execution

For the upcoming lab test this Tuesday, we must complete this question successfully in order to be allowed to take the real exam! Below is the code snippet : * This program calculates the range between the highest and lowest values in a 2-D array */ #i ...

I am struggling to retrieve a value from the angular.forEach function, the flag value is not being obtained. What could be

I'm having an issue with my controller.js file. I can't seem to access the value from the angular.forEach function, specifically the flagvalue isn't being retrieved. Is it because the scope of flagvalue ends when the forEach function complet ...

The positioning of the Kendo UI window is off-center

I have encountered a problem with the alignment of the Kendo Window. There is a simple fiddle available to demonstrate this issue. Despite having ample space for the Kendo window to show without triggering the browser's vertical scroll bar, the cente ...

What is the best way to compare an array with comma-separated values in JavaScript?

I have a scenario where I have two arrays, one for categories and the other for products. Each product contains multiple categories as a comma-separated string. My goal is to match a specific category with each product's product_category value and the ...

bespoke filter designed to conceal any negative figures

I am trying to implement a feature where a text box will display nothing if the ng-model contains a negative value. I want the ng-model to remain unchanged while ensuring that negative values are not displayed. I am looking for a custom filter to achieve t ...