开发者

Javascript: Using object's field's value to determine another object literal's field's name

I want to use object's field's value while creating another object using literal 开发者_JAVA技巧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.


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


Your "test" variable is Array, not Object.

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜