Using JavaScript to assign function arguments based on arbitrary object values

I am facing a challenge with a collection of arbitrary functions and a method that takes a function name along with an object or array of parameters to call the respective function. The issue arises from the varying number of inputs in these functions, some of which have optional fields with default values. I am struggling to find a universal approach to match the parameters with the function inputs.

One workaround for handling array arguments is to directly invoke the function using the ... operator: func(...args). However, this solution falls short when it comes to dealing with objects. Is there a way to align object values with function inputs based on their keys?

To illustrate the scenario further, consider the following abstract example:

const funcs = {
 func1: (arg1, arg2, arg3 = 'something') => .....does something
 func2: () => ....does something
 func3: (anotherArg1) => ...does something

}


function callFunction(method: string, args: unknown[]| object) {

if (Array.isArray(args)) {
 return funcs[method](...args)
}

else (if args instanceof Object) {
 //... Here I need to parse the args and call the function in "funcs" object.
}

}

Answer №1

Simply pass on the second parameter of callFunction(method, ...args)

const functions = {
  function1: (argument1, argument2, argument3 = 'something') => {
    [argument1, argument2, argument3].forEach((arg, index) => console.log(`arg${index+1}:`, JSON.stringify(arg)));
  }
}

function callFunction(method, ...args) {
  return functions[method](...args)
}

const methodToCall = 'function1';
callFunction(methodToCall, [1, 2], {foo: 'bar'})

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

A method designed to accept an acronym as an argument and output the corresponding full name text

Having trouble with my current task - I've got an HTML file and external JS file, and I need a function that takes an element from the 'cities' array as input and returns a string to be used in populating a table. I've set up a functio ...

Turning a JSON dot string into an object reference in JavaScript: A simple guide

Having a JSON object labeled test with values like this: {"items":[{"name":"test"}]}, I need a way to apply the string items[0].name to it in order to search for a specific value (test.items[0].name). Currently, my only idea is to create a function that pa ...

Does Next js Backend support multithreading as a default feature?

As I begin my project, I am utilizing the built-in Node js server within Next js by running the next start command. However, I am uncertain as to whether it has multithreading capabilities. My inquiry is this: Would you suggest sticking with the built-in ...

Revolutionary Knockout-Kendo MultiSelect Feature: Pressing Enter Erases Previously Selected Options

When using the Knockout-Kendo MultiSelect control, I have encountered an issue. If I select a value from the list, then enter a second value and press enter, the previously entered values are removed. VIEW <select data-bind="kendoMultiSelect: { da ...

The accumulation of classes occurs during the cloning process of a template used for a data array

Encountered an issue while duplicating a template div to generate elements for a dataset. The problem arises from classes stacking up when creating elements for each data entry. Sample JavaScript code: $(document).ready(function(){ var data = [ { ...

Contemplate and send an Axios request directly from the browser's URL bar

Seeking JavaScript Logic Assistance I could use some guidance on implementing JavaScript logic, specifically with Vue Router. I don't necessarily need the answer handed to me, just a nudge in the right direction (and apologies if my question is not q ...

Exploring the options variables within CLI commander Js action

As a newcomer to developing CLI apps, I've chosen to work with ts-node and commander. However, I'm currently facing a challenge in understanding how to access the options that users pass into my command action. program .version(version) .nam ...

Understanding how the context of an Angular2 component interacts within a jQuery timepicker method

Scenario: I am developing a time picker component for Angular 2. I need to pass values from Angular 2 Components to the jQuery timepicker in order to set parameters like minTime and maxTime. Below is the code snippet: export class TimePicker{ @Input() ...

The act of exporting an enum from a user-defined TypeScript path leads to the error message "Module not

I have set up a custom path as explained in this particular discussion. "baseUrl": ".", "paths": { "@library/*": [ "./src/myFolder/*" ], } Within this module, I am exporting an Enum. export enum EN ...

How can I pass a value from JavaScript back to the .blade file in Laravel using DataTables?

I have some rows that are being displayed: The DataTable plugin within app.js is responsible for outputting each row. My goal is to target a specific value, ${row.category_id} let TABLE = $('#categoryList').DataTable({ { data: &ap ...

Is it possible to navigate between jQuery EditInPlace fields using the Tab key?

Seeking advice on implementing tab functionality for a page with multiple jquery EditInPlace fields. The goal is to allow users to navigate between fields by pressing the tab key. Currently using the 'jquery-in-place-editor' plugin available at: ...

Can you explain how to add a string array to an HTML div using AJAX?

My output consists of a string array that comes from PHP JSON. I am trying to display this output in an HTML div tabcontent, but I'm unsure of how to achieve this. Below is a snippet of my code - can anyone help me with this? [{"id":"1","p_name ...

Looking for ways to detect memory leaks in your JavaScript application using Selenium?

While utilizing Java and Selenium for automated testing of a JavaScript web application, the issue of memory leaks has arisen. I am interested in ways to effectively test for them. Is there a simple method to obtain memory usage and other profiling data fo ...

Populating the DOM with a mix of strings and HTMLDivElements by iterating through an array using *ngFor

I have a specific layout requirement that needs to resemble this example: https://i.sstatic.net/4kP2q.png The desired layout should utilize CSS properties like display: grid; someFunction(data) { this.data = data; ...

Introducing the concept of type-specific name inclusion

I am currently developing my Angular app using TypeScript with the goal of preventing redundancy through some form of generic handling. Here is where I am starting: class BaseProvider { api_url = 'http://localhost:80/api/FILL_OUT_PATH/:id&apo ...

Begin the initial function again once the second function has been completed

I have 2 functions in my code: function DisplayAltText(){ var CurrentPhoto = $("#DisplayPhoto img").attr("src"); if( $.browser.msie ) { IECurrentPhoto (CurrentPhoto); } if ($(".PhotoGallery img[src='" +CurrentPhoto+ "&a ...

The gridview fails to update when I attempt to click on the update button

Here is my updated code snippet for the GridView After clicking on the update button, the gridview is not being updated and instead reverting back to its previous value. However, the delete option is working correctly. Id = ( ...

The presence of MongoDB dot character in the key name

When working with MongoDB, I ran into an issue where keys with a dot (.) or dollar sign ($) are not allowed for insertion. However, while using the mongoimport tool to import a JSON file that contained a dot in it, surprisingly it worked without any proble ...

Attempting to scroll through a webpage and extract data using Python and Selenium in a continuous manner

Recently, I posed a question (you can find it here: Python Web Scraping (Beautiful Soup, Selenium and PhantomJS): Only scraping part of full page) that shed light on an issue I encountered while attempting to scrape all the data from a webpage that updates ...

Converting and Casting Enums in TypeScript

Is there a way to convert one enum into another when they have the same values? enum Enum1 { Value = 'example' } enum Enum2 { Value = 'example' } const value = Enum1.Value const value2 = value as Enum2 ...