How do I create dynamic names for objects in JS? I am pulling elements from a form (ex: First Name). I would either like to assign a number as the object name or just use the first name.
-
this is a strange request, why would you want to do that?jondavidjohn– jondavidjohn2011-09-28 12:57:23 +00:00Commented Sep 28, 2011 at 12:57
-
maybe I'm taking the wrong approach, but so far i've been pulling the name value from a <form>. Essentially I want create users, and toss them into localStorage as an array, however each time I create a user, it's just the same object being overwritten?zethus– zethus2011-09-28 13:14:33 +00:00Commented Sep 28, 2011 at 13:14
-
add that to your question, I've added an updated answer to reflect your specific situation...jondavidjohn– jondavidjohn2011-09-28 13:19:37 +00:00Commented Sep 28, 2011 at 13:19
Add a comment
|
1 Answer
I'm not sure about variable names, but you can do so with property names
var string = "propertyName";
var obj = {};
obj[string] = "some value";
document.write(obj.propertyName); // some value
As to your specific use case
It might be better to use an array to maintain a list of users...
var users = [];
var newUser = { foo: "foo" , bar: "bar" };
users.push(newUser);
var anotherUser = { foo: "foo" , bar: "bar" };
users.push(anotherUser);
This gives you an array of users.