2

How do i create properties of an object from values of other variables without using the eval() function?

2
  • possible duplicate of Dynamically name a JSON property Commented Aug 16, 2011 at 6:47
  • 2
    I wouldn't agree that this is a duplicate; wildly different roots for this question, though they're ultimately the same solution. Leaving this Question means a bunch of people find it who might not find the other. Commented Aug 16, 2011 at 6:50

7 Answers 7

5

With array notation:

obj[stringvar] = 1;
Sign up to request clarification or add additional context in comments.

Comments

3
var object = {}, stringvar = "name";
object[stringvar] = 1;

Comments

3

You can use other variables as property names like this:

var a = 'property';
var b = {};

b[a] = 'hello';

This can also then be accessed in he following way:

b.property;

Comments

2

Something like this with object literal notation:

var method = 'foo()';
// call it
myobject[method];

So you would do:

object[stringvar] = 1;

Comments

1

Use the bracket notation:

var o = { key: 'value' };
var member = 'key';

o[member] = 'oherValue';

Comments

1
var myobject = {};
var stringvar = "test";
myobject[stringvar] = 1;

Comments

0

Javascript objects allow for on-demand properties creation. Just set the property you want:

var object = {name:'A', id:1};
object.description = "Test";
alert(object.description);

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.