user1546927
user1546927

Reputation: 201

ActionScript object name by variable

In this example:

var poets:Array = new Array();
poets.push({name:"Angelou", born:"1928"});
poets.push({name:"Blake", born:"1757"});
poets.push({name:"cummings", born:"1894"});
poets.push({name:"Dante", born:"1265"});
poets.push({name:"Wang", born:"701"});

Is it possible for 'name' and 'born' to be variables?

Upvotes: 0

Views: 168

Answers (2)

StephenNYC
StephenNYC

Reputation: 1264

If you want to create a function that returns data given the attribute name, you can do something like this:

        public function getDataByAttribute(fieldName:String):Array {
            return poets.map(
                function (item:*, index:int, array:Array):String {
                    return item[fieldName];                         
                }   
            );
        }

        // sample call  
        var results:Array = getDataByAttribute("born");

You can modify it to suit your needs.

To explore Array's functions, see this blog (not mine).

Upvotes: 0

George Profenza
George Profenza

Reputation: 51867

As @RIAstar points out, they are properties of an 'associative array' - your dynamic Object{}:

var poets:Array = new Array();
poets.push({"name":"test","born":"1928"});
poets.push({name:"Angelou", born:"1928"});
poets.push({name:"Blake", born:"1757"});
poets.push({name:"cummings", born:"1894"});
poets.push({name:"Dante", born:"1265"});
poets.push({name:"Wang", born:"701"});

trace(poets[0].name,poets[0].born);

or if a more expanded version:

var prop1:String = "name";
var prop2:String = "born";
var poets:Array = [];
poets[0] = {};
poets[0][prop1] = "test2";
poets[0][prop2] = "1900";

trace(poets[0].name,poets[0].born);

Upvotes: 1

Related Questions