I would like to add property to an object with dynamical property name.
For this I’m using an eval(), but the compiler is returning : Unexpected token . Is what i’m doing possible, or eval() can’t be used for objects like str vars
Here is a bit of my code
var options = {}; // Creating empty object
$("#selAdresse, #selCP, #selVille, #selPays, #selNom, #selDescription").live('change', function(){
var opt = eval("var options.lol"); // The evil eval();
opt = "Test"; // Trying to set options.lol = "test"
console.log(options); // Returning an empty object... Nothing change
});
You don’t use
varto add a property to an object. You use var to initially declare a variable:Adding properties is simple:
If you have a string containing the property name, you use square bracket notation:
Edit:
Based on your comment to kbok, square bracket notation is what you want:
End Edit
To be specific to your question (though you shouldn’t be doing it and there are ways to avoid it), the syntax of your eval would look like: