1

I would like to make an Object that has key names taken from a variable. Probably this is not clear enough, so let me make an example.

I have two variables var str1:String = 'firstKey'; and str2:String = 'secondKey';

How can I make an object that would look like:

var obj:Object = {firstKey: 'some value', secondKey: 'some other value'}, note that firstKey and secondKey are values of variables str1 and str2.

Doing obj = {str1: 'some value', str2: 'some other value'} does not yield a result that I would like

Thanx a bunch for answers! Ladislav Klinc

3 Answers 3

5

I'm not sure I understood correctly, but this might be what you want:

var str1:String = 'firstKey';
var str2:String = 'secondKey';

var myObj:Object = {}; // shorthand for a new object
myObj[str1] = 'some value';
myObj[str2] = 'some other value';

The strings within brackets are expanded, so really this is what happens:

myObj.firstKey = 'some value';
myObj.secondKey= 'some other value';
Sign up to request clarification or add additional context in comments.

Comments

1

As Lex suggested, just split() a String by a delimiter into an Array and use that to populate your object.

e.g.

//get the values as arrays
var keys:Array = String('firstKey,secondKey').split(',');
var values:Array = String('some value,some other value').split(',');
var keysNum:int = keys.length;
//populate the object
var obj:Object = {};
for(var i:int = 0; i < keysNum; i++) 
    obj[keys[i]] = values[i];
//test
for(var k:String in obj)
    trace('key: ' + k + ' value: ' + obj[k]);

HTH

Comments

0

I think you have to use an array for that. So your object has an array (with the key strings as offset). I'm not sure what the AS 3 syntax is for that, but I'm sure that it's possible.

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.