Is there a way to 1) log the names of parameters in a function using console.log? 2) pass a string as an argument to a function, but transform it into an object reference?

I've been pondering this question for quite some time. Grateful to anyone who can provide some insight!

let foo = {key: 'value'};

Scenario 1:

const stringToObject = function(objectName){
  console.log(someUnknownFunction(objectName));
};

stringToObject('foo');  // displays an object: {key: 'value'}

Scenario 2:

const objectToString = function(objectName){
  console.log(someUnknownFunction(objectName));
};

objectToString(foo);  // shows a string: 'foo'

Answer №1

If you're looking for a solution, using the eval function might be your best bet. However, keep in mind that it can execute any code provided to it, making it potentially risky.

var foo = {key: 'value'};
var stringIntoReference = function(nameOfObject){
  console.log(eval(nameOfObject));
};
stringIntoReference('foo'); // {key: 'value'}

It's important to note that when using eval within stringIntoReference, the scope may differ from where you call the function.

The second option isn't straightforward. The function receives the value after identifier resolution. You could attempt to manipulate scope with a with statement, but it might not align with your intentions.

var referenceIntoString = function(nameOfObject) {
  console.log(nameOfObject);
};
var p = new Proxy({}, {
  has: (_, prop) => prop !== "referenceIntoString",
  get: (_, prop) => prop,
});
with(p) {
  referenceIntoString(foo); // 'foo'
}

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

Change the styling of a DIV depending on the character count of a text within another DIV using JQuery

My website contains a series of div elements that display an image, title, and excerpt. Some of the content divs have titles that span two lines, while others have shorter one-line titles. I would like to add a different class to the excerpt div if the tit ...

Obtaining the identifier of dynamically inserted text components

One of the features on my ASP page allows users to load items into textboxes. Since the number of elements will vary and is not known at the outset, I utilize Javascript to generate new textboxes as needed. <script> var sessionId = 0; function cre ...

Can a HTML element be transferred from one div to another div in React?

Is there a way to transfer an HTML element from one div to another in React and add animation during the transition process? Any suggestions on how to achieve this would be highly appreciated. ...

Encountering a "Error 404: Page Not Found" message when trying to request a json object from a node server

Working on a RESTful API, I have set it up to run on node.js using express.js, mongodb with mongoose for object modeling, and body-parser for passing HTTP data. However, whenever I start the server and try to access the specified IP address, I encounter a ...

Updating PHP database with a countdown timer

I am looking to create a JavaScript function that will count down from one hundred seconds. After writing the countdown code, I want to store the remaining time value in a database every second. Here is an example of what I hope to achieve: For each secon ...

Formatting Date and Time in the Gridview of my Asp.net Application

I have been using this format to display the date and time in a grid. The issue I am facing is that I cannot retrieve the exact HH:MM from the database. Even though the database shows 11:11, my grid is displaying 11:03 instead. Here is the value stored in ...

Preventing the pull-down-to-refresh feature on Chrome mobile can be achieved by adjusting the

Looking for a way to prevent the pull-down-to-refresh feature on mobile Chrome, especially iOS Chrome? My web application utilizes vertical panning events with device-width and device-height viewport settings, but each time I pan down, mobile Chrome refres ...

Filling in input field attributes using a custom directive

Here is a JSFiddle link for reference: http://jsfiddle.net/DfLdF/ The issue I am facing involves a controller wrapping a form with certain logic that cannot be defined within the directive hash as a controller. Specifically, I need to dynamically populat ...

Troubleshooting Problem with Bootstrap CSS Menu Box Format

I'm having trouble creating a simple menu for my Bootstrap site. What I want to achieve is something like this: https://i.sstatic.net/abZXC.png This is what I have accomplished so far: https://i.sstatic.net/JFVC2.png I've attempted to write th ...

Is there a way to change or delete this inline javascript using Greasemonkey?

I stumbled upon this script within the head of a website: <script type="text/javascript" > function Ext_Detect_NotInstalled(ExtName,ExtID) { } function Ext_Detect_Installed(ExtName,ExtID) { alert("We have detected an unauthorized extension. Pl ...

How to prevent a directory from being copied in webpack within Vue CLI

Currently, I am working on a Vue3 project created using Vue CLI 5.0.1 In my setup, there is a public folder that contains static assets necessary for serving the application. However, this folder is quite heavy, around 1GB in size. Whenever I run the npm ...

Switch Out DIV Tag After Clicking It Three Times

I am attempting to replace a specific div element with a different one after it has been clicked on 3 times. This is the sole task I am aiming to achieve through the code. I have searched for code snippets that accomplish this, but all of them immediately ...

Every time I attempt to launch my Discord bot, I encounter an error message stating "ReferenceError: client is not defined." This issue is preventing my bot from starting up successfully

My setup includes the following code: const fs = require('fs'); client.commands = a new Discord Collection(); const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js')); for(const file of com ...

Managing a variety of PHP responses using AJAX

I am currently in the process of designing PHP pages for form processing. On these pages, I aim to redirect if the result is successful or display an error message in case of any errors. The structure of the pages is as follows: $arg = $_POST["arg"]; if ( ...

Puppeteer: Easily choosing a dropdown selection by its displayed text

When using Puppeteer, you have the ability to choose an option from a dropdown by specifying the value as a parameter: page.select('select#idOfSelect', 'optionValue'); I'm wondering if there is a way to select an option by its te ...

Converting and storing Canvas data as a blob, and then saving the blob as

There is a clickable icon on the page that triggers an action when clicked. Currently, the icon is set as an anchor tag. However, I want to change it to a div like all the other icons in my UI. But for some reason, the following code isn't working. W ...

Exploring the process of creating a interactive rectangular border on an image with JavaScript

I'm currently working on a project that requires me to draw multiple bounding boxes interactively within an image displayed on a web browser. After drawing the bounding boxes, I will need to extract their coordinates. Are there any suggestions for a J ...

What do the two arrows represent in a higher order function in React using Javascript?

I've been exploring this example HOC function, but I'm struggling to understand the significance of the two arrows, especially the second one where we are de-structuring children and props. const CustomHOC = (InnerComponent) => ({children, .. ...

Press the Text and Alter Text with React

I'm having an issue with the onClick event using React hooks. My goal is to have the text change to a different one when the user clicks, and then revert back to the original text on another click. For example, clicking "Change First" should switch it ...

Having issues with jQuery's .hover and .mouseleave functions causing unintentional looping. Any suggestions on how to resolve this

What I want to achieve: When hovering over the image, it fades out. Text should fade in after the image fades out. Text should fade out when the mouse leaves. The original image should fade back in. End with the original image and no text displayed. Iss ...