0

I have a variable containing a string. This string is itself the name of another object.

say

const myObject = {"some": "Object in JSON format"};

const myObjectName = 'myObject';

How can I use the string contained in the variable 'myObjectName' to call a function manipulating myObject?

2
  • You can't touch a variable name using a string as far as I know Commented Nov 3, 2020 at 16:19
  • Seriously? It's possible the function doesn't exist but doesn't that make the language non Turing complete? Commented Nov 3, 2020 at 16:20

1 Answer 1

2

const myObject = {"some": "Object in JSON format"};
const myObjectName = 'myObject';
function myFunction (obj) {
   console.log(obj);
}

eval(`myFunction(${myObjectName})`);

This works but eval is dangerous and should be avoided

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.