tags:

views:

202

answers:

3

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  A: 
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

Marius
It somehow seemed to work for me :). Tested and removed it from the question as wrong code.
Li0liQ
+1  A: 

Your "test" variable is Array, not Object.

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

Beresta
A: 

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

Cheers

RameshVel

Ramesh Vel