0

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.

3
  • this is a strange request, why would you want to do that? Commented 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? Commented Sep 28, 2011 at 13:14
  • add that to your question, I've added an updated answer to reflect your specific situation... Commented Sep 28, 2011 at 13:19

1 Answer 1

3

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.

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.