0

I want to use object's field's value while creating another object using literal notation:

var T = {
 fieldName : 'testField'
};
/*
// Doesn't work.
var test = {
 T.fieldName : 'value'
};
*/
// Does work.
var test = [];
test[T.fieldName] = 'value';
alert(test.testField);          // test

But it doesn't work.
Is there a way to solve this issue or using square brackets is the only way out?

Upd.: Removed non-working code.

2
  • 2
    You haven't tried to run the code you posted, have you? Commented Dec 21, 2009 at 11:12
  • Oops, it somehow seemed to work for me. Removed wrong code. Commented Dec 21, 2009 at 11:23

3 Answers 3

2
var T = {
 fieldName : 'testField'
};
var dummy = T.fieldName;        // dummy variable
var test = {
 dummy : 'value'
};
alert(test.testField);          // test

That should not work. The value 'value' will be stored in test.dummy, not test.testField. The way to do it would be:

var T = {
 fieldName : 'testField'
};
// Does work.
var test = {};
test[T.fieldName] = 'value';
alert(test.testField);          // alerts "value"

Which is what you already have

Sign up to request clarification or add additional context in comments.

1 Comment

It somehow seemed to work for me :). Tested and removed it from the question as wrong code.
2

Your "test" variable is Array, not Object.

You should create "test" like "= {}" instead of "= []".

Comments

0

One possible way is.

var T={
    testField : 'testField'
};

     eval ('var test = {' + T.testField + ':' +  value + '}');

And you make this generic, something like this

function MakeVar(varName,fieldToUse,valueToPass)
{
      var res = 'var ' +varName+ '= {' + T.testField + ':' +  value + '}'
     eval(res);
}

var T={
    testField : 'testField'
};


     MakeVar('test',T.testField,'value');
     var outt=test.testField;

Hope this helps

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.