Utilize loop iteration to execute a function with the same name - JavaScript

In my init function, I have a loop:

  fruits = {
    apple: { color: 'green' },
    banana: { color: 'yellow' },
    kiwi: { color: 'green' }
  }

  ngOnInit() {
    for ( let fruit in this.fruits ) {
      if ( this.fruits[fruit].color === 'green' ) {
        // I want to actually invoke the functions
        this[fruit]()
      }
    }
  }

I am attempting to call functions that meet a specific condition. The functions will be named after the "loop iterator," but I'm struggling to figure out how to dynamically make the call.

  apple() { ... }
  banana() { ... }
  kiwi() { ... }

Therefore, according to the loop's condition, apple() and kiwi() should be executed if they are green fruits.

Question: How can I correctly construct the function call within the ngOnInit function?

I have tested: this[fruit]() , this.fruit() , this['fruit'] . Which option is correct?

Answer №1

In my opinion, that is the correct way to achieve your desired outcome

const vegetables = {
  broccoli: { color: 'green' },
  carrot: { color: 'orange' },
  spinach: { color: 'green' }
}

ngOnInit() {
  for ( let veggie in this.garden ) {
    if ( vegetables[veggie].color === 'green' ) {
      // Utilizing the current iterator here
      this[veggie]();
    }
  }
}

Answer №2

To make your code functional, you must execute this[key_in_obj]() in order to run the function.

const items = {
    chair: { material: 'wood' },
    table: { color: 'brown' },
    lamp: { power: 'electric' }
  }
for(let item in items) {
  console.log(item);
  if (items[item].material === "wood") {
    this[item]();
  }
}

Answer №3

It seems like you're attempting to implement some logic based on a static condition using multiple functions named according to the parameter value in the iterator. The recommended approach is to create a single function and pass the fruit as a property. Then, you can handle the logic within the function based on the property value itself using a switch statement (or if else conditions).


const fruits = {
    apple: { color: 'green' },
    banana: { color: 'yellow' },
    kiwi: { color: 'green' }
}
handleGreenFruit(fruit: string) {
    switch (fruit) {
        case 'apple':
            console.log('do apple stuff')
            break;
        case 'kiwi':
            console.log('do kiwi stuff')
            break;
    }
}
ngOnInit() {
    for (let fruit in this.fruits) {
        if (this.fruits[fruit].color === 'green') {
            this.handleGreenFruit(fruit);
        }
    }
}

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

When I set the width of my script to 100% in CSS, it causes the width to become distorted

I encountered an issue with my Div Slider that swaps out Divs on click. When I modified the CSS to include the following: .hslide-item {width: 100%}; The script started ignoring the entire div width. I am looking for a solution where the .hslide-item ca ...

Transferring data using Ajax in a contact form PHP file

I recently started learning about AJAX and came across a code snippet online for sending data to a PHP file using AJAX. However, I'm facing an issue where I'm not sure if the data is being submitted or what is happening. The alert box doesn' ...

Insert a parameter or substitute the existing value if detected

Trying to create a JavaScript regex that searches for a parameter in a URL and replaces its value if found. If the parameter is not found, it should be added to the URL. Here are a couple of scenarios: http://www.domain.com/?paramZ=123456 https://www.dom ...

Display JSON data using Vue.js

Trying to display JSON file results using Vue.js, with the goal of showing the result in a value. Here is the code snippet: data () { return { fetchData: function () { var self = this; self.$http.get("/api/casetotalactivation", functio ...

Node.JS: Combining Multiple Files into a Single Output File

Currently, I am in the process of building a data pipeline using Node.js. While I acknowledge that there are better ways to approach this, I am determined to implement it and make improvements as I go. Here's the scenario: I have a collection of gzi ...

Xpath: Choosing the parent node value in xpath when a child node is present

Trying to generate an HTML table using JavaScript based on XML data. When a child element like //host exists, I need to extract the value of a parent element called "name" from a different ancestor using XPath The required channel name can be found in th ...

Is a shifting background image possible?

Can anyone shed some light on how the dynamic background image on this website is created? Is it a JavaScript plugin, a simple .gif, or something else entirely? Appreciate any insights! ...

The interconnected nature of multiple asynchronous tasks can lead to a render loop when relying on each other, especially when

My asynchronous function fetches data in JSON format from an API, with each subsequent call dependent on the previously returned data. However, there are instances where I receive null values when trying to access data pulled from the API due to the async ...

Experiencing a lack of information in express?

Whenever I attempt to send a POST request (using fetch) with the body containing the state of the application, I receive an empty object on the server side. What am I doing wrong here? I should be receiving the object with the properties name, username, an ...

What is the most efficient method for storing and accessing a large matrix in JavaScript?

With 10000 items, creating a matrix of 10000 rows * 10000 columns using a one-dimensional array would be massive. Additionally, setting specific values to cells (i,j) where 0 < i, j < 10000 would require a large number of iterations. I am facing cha ...

How can I remove the script from Response.Write?

Instead of using Response.Write to test some values in code with an alert box, I tried writing dynamic javascript directly into the page. Even after reverting the code, rebuilding, and clearing all temp data from IE, the alert still pops up. I followed a ...

Can you provide an example and explain the functions `getOptionSelected` and `getOptionLabel` in Material UI?

While going through the Mui Documentation, I came across the Autocomplete component section and found two interesting props: getOptionLabel and getOptionSelected. Although I read their definitions, I'm still struggling to grasp them fully. Can someone ...

Creating a universal header for all webpages in Angular JS by dynamically adding elements using JavaScript DOM manipulation techniques

I have successfully created a json File containing an array of "learnobjects", each including an id, name, and link. Check out my plnkr example var myMessage = { "learnobjects": [{ "id": "1", "name": "Animation-Basics", "link": "animation_bas ...

What is the process of displaying events from components within ng2 submodules?

My dilemma involves two components with straightforward output events and handlers. I am attempting to pass a value from a child submodule to a component within my app.module. Here is the snippet of code from my app.component.ts: @Component({ selector: ...

Position control in the Google Maps V2 interface

I am currently utilizing Google Maps API v2 with the default UI because I find the controls to be more visually appealing when set to default. <script type="text/javascript"> var map = null; function load() { map = new GMap2(document.get ...

Linking AngularJS directives with HTML elements following an AJAX call

Having trouble getting the 'customers-invoice.html' file to work with my Angular app after loading it through ajax. Any suggestions on how to bind them together?” <body ng-cloak ng-app="myApp"> <main id="main"> <div ...

Connecting an HTML box to a JavaScript function for the desired outcome: How to do it?

My goal is to connect the input box with id="b" (located inside the div with id="but1") with a JavaScript function that calculates values within an array. Although my junior logic review didn't detect any issues in the code, what mistakes could I have ...

What is the best way to retrieve children generated by a custom HTML component using idiomatic React methods?

I'm currently working on developing a search bar with predictive text input using a custom HTML component. The component generates multiple plain HTML children that I need to manipulate in order to achieve the desired functionality. Specifically, I ha ...

Can anyone provide a solution for fixing TypeScript/React error code TS7053?

I encountered an error message with code TS7053 which states: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ name: string; isLandlocked: boolean; }'. No index signa ...

Utilizing useEffect Hooks to Filter Local JSON Data in React Applications

For my engineering page, I have been developing a user display that allows data to be filtered by field and expertise. Fields can be filtered through a dropdown menu selection, while expertise can be filtered using an input field. My initial plan was to ...