views:

481

answers:

2

Hi.

I need a function that gets two array parameters of the same length: property-names (Strings) and property-values.

the function should create an object with properties so that, for an example, after calling

var obj:Object = makeObject({"prop1","prop2"},{1,2});

the testing condition (obj.prop1 == 1 && obj.prop2 == 2) should be true.

I'm led to believe that this should be an easy one if you know your actionscript - maybe it's just a syntax thing.

late addition
after re-reading my question, it appears It wasn't very easy to understand.
my problem was naming properties based on runtime values, that is, using a string parameter to refer a property name.

+2  A: 

Not sure I understand your question, but you can create the Object using an Object literal:

var item:Object = {prop1: 1, prop2: 2};

trace (item.prop1 == 1 && item.prop2 == 2) // true
Eric Belair
I believe the poster wants a way to create an object with keys that are unknown at compile time, so the syntax you're describing won't work in this case. The key names are simply strings passed into a function.
Matt Dillard
+2  A: 

An Object can be treated like a map (or associative array) with strings for keys - I believe that's what you want to do. You can read up on associative arrays in Flex in Adobe's documentation.

private function makeObject( keys : Array, values : Array ) : Object
{
    var obj : Object = new Object();

    for( var i : int = 0; i < keys.length; ++i )
    {
        obj[ String(keys[i]) ] = values[i];
    }

    return obj;
}

This will create a new Object with keys equal to the values in the first array, and values equal to the items in the second array.

Matt Dillard
bzlm
It should be, unless I'm overlooking a mistake in my code (which is certainly possible...). An object's properties can be accessed in multiple ways; both the associative array syntax and the Object.Property syntax resolve to the same thing, if that's what you're asking.
Matt Dillard
thanks. I had a hard time explaining my question (perhaps that's the reason I couldnt google it up), but obj[ String(keys[i])] is exactly the answer I was looking for.
Amir Arad