Retrieving the passed argument variable and utilizing it as a key in a map

I've been working on a JavaScript project recently and I've encountered a situation where I believe my code could be significantly reduced - up to 50% - if I could access the passed arguments to a function and use them as keys. Since I'm still new to JavaScript, some clarification would be greatly appreciated.

Here is what I am trying to achieve

Foo(arg1,arg2){console.log(Map[arg1]);

My goal is to pass arg1 as a key rather than a value of arg1.

Is there a way to accomplish this?

Answer №1

If you are in need of variable names, you can use a method like the one demonstrated below:

function getVariableNames(arg1, arg2, Arg3){
  var Args = Array.apply(null, arguments);debugger
  var ArgNames = (getVariableNames+"").match(/\(([.\s\S]*?)\)/)[1].replace(/[\s ]/g,"");
  ArgNames = !ArgNames ? [] : ArgNames.split(",");
  for(var i in ArgNames) console.log(ArgNames[i]+": "+Args[i]);
  console.log("Value of arguments: "+Args);
  console.log("Name Of arguments: "+ArgNames);
};
getVariableNames(100,40,"BTTOLA");


This approach works well even if the function has no arguments or is defined within a few lines.

The following types of functions are supported by this approach:

function example(a, b){...};

function example(
   a, 
   b
 ){
   ...
};

var example=function(a, b){...};

Alternatively, for an Arrow function like this:

var example = (a, b) => {...}

You can implement it in a similar way (which is effective for both Arrow and simple functions):

var example = (arg1, arg2, Arg3) => {
  var ArgNames = (example+"").match(/\(([.\s\S]*?)\)/)[1].replace(/[\s ]/g,"");
  ArgNames=ArgNames?ArgNames.split(","):[];
  console.log(ArgNames);
};
example(100,40,"BTTOLA");

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

Should I refrain from storing user files on my server?

Greetings! I am currently working on an Express js + React js application and using MySQL for database management. I have successfully stored user information like email, hashed passwords, and user IDs in the database. However, now I want to create ...

Tips on resolving the Hydration error in localStorage while using Next.js

Having issues persisting context using localStorage in a Next.js project, resulting in hydration error upon page refresh. Any ideas on how to resolve this issue? type AppState = { name: string; salary: number; info: { email: string; departme ...

Use Javascript to conceal a div element if there are no links present

I am working on a website using ModX CMS and I am attempting to hide or remove a div element when it does not contain any anchor tags. How can I achieve this? I have already attempted the following code without success: jQuery(function($) { if ($(".pages ...

Unveiling the significance behind the utilization of the.reduce() function in conjunction with Object.assign()

After consulting the method/object definitions on MDN, I am attempting to create a simplified step-by-step explanation of how the script below (referenced from a previous post) is functioning. This will not only aid in my understanding but also help me ada ...

What is the method for retrieving post ID with the Google Feed API?

I am currently utilizing two different JS codes to dynamically load posts from my Wordpress website: Code 1: JSON API <script src="http://howtodeployit.com/category/daily-devotion/?json=recentstories&callback=listPosts" type="text/javascript">& ...

What is the process of incorporating a select form within a component?

I am currently working on creating a user registration form. Once the form is filled out and the submit button is clicked, I need the values from the form to be displayed in a specific <p id="data></p> component. Can anyone assist me with this ...

Implementing personalized callback methods for AJAX requests in Prototype

After refactoring my code to use proper objects, I am facing an issue with getting Prototype's AJAX.Request to work correctly. The code snippet below is functioning within the context of YUI's DataTable: SearchTable.prototype.setTableColumns = f ...

I possess a certain input and am seeking a new and distinct output

I am looking to insert a word into an <input> and see an altered output. For example, Input = Michael Output = From Michael Jordan function modifyOutput() { var inputWord = document.getElementById("inputField").value; var outputText = "print ...

Indeed, verifying parent.parent access

Currently, I am utilizing the yup module to validate my form. My objective is to access the parent in order to test the value. Below is my schema: enabled: yup.boolean(), contactDetail: yup.object().shape({ phoneNumber1: yup.string().nullable(), pho ...

What is the best way to add a URL dynamically when a click event occurs?

Here is the code where I am making an API call: export const filteredProducts = (e) => { const radio = e.target.checked; return dispatch => { dispatch({type: actionTypes.TOGGLE_LOAD}); axios.get(radio ? `/store?limit=9&skip=0&subc ...

What is causing the router.events to not fire for FooComponent in my Angular project?

Upon opening the following link , the eventsFromFoo entries in the console are nowhere to be found. It appears that this.router.events is failing to trigger for FooComponent. Any insights on why this might be happening? I am in urgent need of capturing t ...

Leveraging JQueryUI for an audio Seek feature, and dynamically connecting a fresh slider to the <audio> element whenever a song is swapped out

Thanks for taking a look at my question. The code snippet can be found HERE. I'm in the process of creating an audio player to handle multiple songs on a single page using JQueryUI Slider and HTML5 Audio, with one Audio element and several sliders. ...

Encountering a Microsoft error while trying to install jsdom with node.js

I'm currently in the process of setting up jsdom on my system. I found a helpful guide at but encountered the following issue: C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.Cpp.InvalidPlatform .Targets(23,7): e ...

Obtain data attributes using JQuery's click event handler

I'm facing an issue with a div structure setup as follows: <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class=& ...

Having trouble retrieving POST data with the Webextensions API

Looking to retrieve POST data using a Webextensions API on page load. Implemented a background script with the code below: browser.webRequest.onBeforeSendHeaders.addListener( getPostData, { urls: ['<all_urls>'], types: ["main_fr ...

What steps can be taken to enhance cleanliness and efficiency, and what are some recommended practices to adhere to?

Currently, I am in the process of developing a user authentication system on the backend. Specifically, I have implemented a POST method for registering new users. userRouter.post("/", expressAsyncHandler(async (req, res) => { try { const { na ...

How to iterate and apply styles to properties of objects in an array using Vue.js?

Currently, I am working with Vue.JS and facing some challenges while outputting data using the v-for loop. My objective is to repeat a 'base' item with unique information. You can refer to the image below for better understanding. Progress has ...

Tips for modifying a state array in Vuex

I have the ability to add and remove entries, but I'm struggling with editing. How can I achieve this using VUEJS, VUEX, and JavaScript? For adding entries, I know I should use PUSH, and for removing entries, SPLICE works fine. But what about editing ...

How can I ensure that the appropriate 'this' is accessed within a callback function for an AJAX request?

When working with a callback function, I am having trouble accessing this. Instead, it seems to be pointing to the AJAX object rather than the object that initially invoked the onClickEmail function. I attempted to store a reference in a variable called th ...

Show an error message in a popup window, following a validation error in Laravel

I am facing an issue with displaying error messages in the update modal form. I am using Laravel request for validation and AJAX to submit the form inside a modal. My goal is to show the error message for each field that is inputted incorrectly. However, i ...