dev
dev

Reputation: 1507

Variable Key in Key-Value pairs

So the code that I have working is something like this:

var name:String = "Cashier";
var data:String = "Pay";

arr.push({name:tmpName, data:tmpData});

name, tmpName, data and tmpData are all variables. However this shows up as "name" and "data" being the key instead of "Cashier" and "Pay"

tmpName & tmpData are setting correctly, however.

Any help would be greatly appreciated.

Upvotes: 3

Views: 2784

Answers (2)

OMA
OMA

Reputation: 3691

I'm doing a PHP to AS3 code conversion and I've created this function to help me with associative arrays declared with dynamic keys (it should work in JavaScript with just a few changes). It might help you as well.

function array(... keysAndValues):Object // Emulates PHP's associative arrays
{
    var obj:Object = {};
    if (keysAndValues.length % 2 != 0)
    {
        throw new Error('The number of arguments of array() must be even. To create a non-associative array, use "new Array()" or "[]".');
    }
    for (var i:int = 0; i < keysAndValues.length; i += 2)
    {
        obj[keysAndValues[i]] = keysAndValues[i + 1];
    }
    return obj;
}

That way if I have the keys and values in strings...

var key1:String = 'FirstKey', value1:String = 'aaaaa';
var key2:String = 'SecondKey', value2:String = 'bbbbb';

I can just do...

var myAssoc:Object = array(
    key1, value1,
    key2, value2
);

Which is really similar to PHP's syntax:

$myAssoc = array(
    $key1 => $value1,
    $key2 => $value2
);

So you just have to substitute the " => " in a PHP assoc array with ", " when using this array() method. Just make sure the number of arguments is even and you don't mix up keys and values, as it goes key, value, key, value, ...

You can use this lowercase array() method for PHP-like associative arrays and AS3's regular uppercase new Array() declaration for numeric arrays (or just use []). Just remember that when using lowercase array() you're really getting an Object, not an Array, so you should declare the variable which stores it accordingly as an Object.

Upvotes: 1

Marty
Marty

Reputation: 39456

You'll need to use square bracket notation for dynamically named keys:

var object:Object = {};
object[name] = tmpName;
object[data] = tmpData;

arr.push(object);

Upvotes: 2

Related Questions