I wanted to know if I can define an object in javascript with string templates (``) and if so, what would be the correct syntax? I mean something like:
var mi_objeto = `{prop: 1, atr: 2}`;
I wanted to know if I can define an object in javascript with string templates (``) and if so, what would be the correct syntax? I mean something like:
var mi_objeto = `{prop: 1, atr: 2}`;
The way to do this is to use
eval
`` to evaluate the expression. String templates return a string, and you pass that string as an argument toeval
:Although it looks like it should work, this gives a syntax error (I don't know the reason for it). The way to fix it is to wrap the object in parentheses so that the evaluation succeeds:
If you have the string with the object inside it stored in a variable, you just have to concatenate the parentheses:
PS: The information has been obtained from this SO entry in English: https://stackoverflow.com/questions/4010775/javascript-eval-and-object-evaluation