I wanted to know if I can define an object in javascript with the text 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 the text 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 between ''. Text string templates return a string of text, and that string is passed as an argument to eval
:
var mi_objeto = eval('{prop: 1, atr: 2}');
Even if it seems to work, this gives a syntax error (I do not know why). The way to solve it is to wrap the object in parentheses so that the evaluation is carried out correctly:
var mi_objeto = eval('({prop: 1, atr: 2})');
console.log(mi_objeto);
If the string with the object inside it is stored in a variable, all you have to do is concatenate the parentheses:
var objeto_cadena = '{prop: 1, atr: 2}';
var mi_objeto = eval("("+objeto_cadena+")");
console.log(mi_objeto);
PS: The information has been obtained from this SO entry in English: link