What is the correct way to invoke a function with a string contained within an object?

Looking for a way to call a function from an object using a string. Here's an example scenario:

type = 'human'

json: {
    action: 'run',
    type: this.type, //<- Need to call the function associated with the variable type
    'Human', or whatever value the variable type holds.
}

The goal is to parse the string and invoke the matching function.

This is specifically for Angular. I've attempted using window['function'] but Angular throws an error saying it's not a function.

Appreciate any help on this! Thank you!

Answer №1

It seems like what you're trying to say is that you have an object containing a property, and the value of that property is also the name of the function you wish to invoke.

Let's consider an array of objects as an example:

const items = [{func:'a',val:5}, {func:'b',val:7}];

You want to loop through these objects and call the function 'a' for the first one and the function 'b' for the second one.

One approach is to define your functions within an object:

const actions = {
  a: function(value) {
    console.log('executing function a');
    console.log(value);
  },
  b: function(value) {
    console.log('executing function b');
    console.log(value);
  }
}

Then, you can achieve this by doing something similar to the following:

items.forEach(item => actions[item.func](item.val));

Answer №2

Typically, the key is parsed in order to invoke a corresponding function.

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

Tips for expanding the HTTP header size within Next.js

Can someone provide assistance for increasing the HTTP header size in my Next.js app? The current size is set at 16384 and I am unable to execute the necessary command node --max-HTTP-header-size=24576 server.js. Looking for help from someone with more e ...

How to verify the existence of a YouTube video ID using JavaScript

In this code snippet, I am using the video ID 'TOwd30wXc-0' from YouTube: $.ajax({ url: "http://gdata.youtube.com/feeds/api/videos/"+realurl+"?v=2&alt=json-in-script", dataType: "jsonp", contentType: "application/json ...

The jQuery toggle functionality seems to be malfunctioning when used alongside various other JavaScript code in close proximity

I am currently experimenting with a basic jQuery toggle button that I found while browsing through an example at How can I dynamically create derived classes from a base class: <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery ...

Issue in Three.js: The lower part of the mesh is not rendering

After converting a mesh from .obj to json using the official converter (https://github.com/mrdoob/three.js/tree/master/utils/converters/obj), I noticed that the mesh displays correctly from one side, but not the other. This seems to be due to the fact that ...

Issue with label alignment in Chart.js after updating through ajax call

Utilizing chart.js allows me to showcase real-time data... var initiateAJAX = function() { $.ajax({ url: url, success: function(){ var currentTime = ++time var currentValue = Math.random()*1000; ...

Error retrieving individual user information from the list via REST API

routes user.js view layout.ejs user.ejs users.ejs app.js REST API - "" I am facing an issue with two GET requests. In users.ejs, I am rendering three dynamic buttons with specific href values. In user.ejs, I am rendering a single user. ...

What is a specialized type that exclusively swaps out the methods within an interface for a different type while keeping everything else intact?

I am in the process of developing a versatile type that can accept an interface, type literal, or a class. The desired outcome is for the resulting type to retain the original properties as well as have the methods set to jest.Mock type MockedType<T> ...

What is the best way to display a Base64 image in a server-side DataTable?

This HTML code is designed to load server-side data into a table. The data is retrieved from the controller using AJAX requests. <script type="text/template" id="tablescript"> <td><%=Name%></td> <td><%=PhoneNumber%> ...

Within Codesandbox using Vue, the error message 'The property or method "children" is not defined in the instance, but is referenced during rendering.' appeared

Currently, I am in the process of creating a versatile State Manager that can seamlessly integrate with various Frontend Frameworks, including Vue. In order to showcase how the State Manager can be utilized within Vue, I have set up a simple codesandbox de ...

Using JavaScript to execute a PHP function for updating or inserting data into an SQL database

I seem to be facing some minor issues at the moment. I have this JavaScript function that updates the stream of the VLC web plugin. However, what I am really trying to do is incorporate a way to input data into my database to keep track of how many viewers ...

unable to connect a value with the radio button

I am struggling to incorporate a radio group within a list of items. I am facing difficulty in setting the radio button as checked based on the value provided. Can anyone provide me with some guidance? Here is the HTML code snippet: <div *ngFor=" ...

Crockford's system for safeguarded entities

Despite the abundance of questions and resources related to "Javascript: The Good Parts," I am struggling to comprehend a specific sentence in the book. On pages 41-42, the author defines the serial_maker function as follows: var serial_maker = function ( ...

Does the String.replace() function in Javascript have the capability of incorporating line breaks?

Is it possible to use the String.replace() method in JavaScript to replace any character with a line feed symbol? For example: newString = oldString.replace(/x/, "linefeed character (\n)"). ...

Show a variety of randomly selected pictures from various sources using the command image/next

I'm in the process of building a basic news aggregation website using Next.js. I’ve run into an issue where I need to include specific domains in my next.config file for the Image component to work properly. The problem is, the URLs for the images o ...

arrange data based on table heading using vue.js

I've recently upgraded to Vue 2.x and found out that the orderby directive is no longer supported as per this documentation. I'm trying to avoid adding another JavaScript library, but if using lodash is the only option, I'm willing to give ...

Stop the form from submitting when the Enter key is pressed

I am experiencing an issue with my form that contains around 10 input text boxes. When I press the enter key from an input text box, it skips the text boxes in between and goes directly to the submit button. This problem occurs only when using the keyboard ...

iOS iframe remains unscrollable only when switching from portrait to landscape orientation

I have a scrollable iframe set up on iOS like this: <div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; overflow: scroll; -webkit-overflow-scroll: touch; ..."> <iframe style="height: 600px, ..."> </iframe> </d ...

"When using FireFox, you can easily create a hyperlink that scrolls to a specific section of a webpage,

I have created a style for image button: .sticky { position: fixed; top: 50px; width: 120%; z-index: 1; } @media screen and (min-device-width : 100px) and (max-width: 600px) { .sticky{ display:none; } } and also implemented a script for it: ...

Creating custom views in Angular 8 based on user roles through directives

After reviewing an example on how to display components based on a user's role at this link: I'm encountering compilation issues due to missing arguments in the constructor within has-role.directive.spec.ts. The constructor in has-role.directive ...

JavaScript's version of "a certain phrase within a text"

If I'm working in Python and need to verify if a certain value is present in a string, I would use: if "bar" in someString: ... What would be the equivalent code in Javascript for this task? ...