I have an Array Collection with any number of Objects. I know each Object has a given property. Is there an easy (aka "built-in") way to get an Array of all the values of that property in the Collection?
For instance, let's say I have the following Collection:
var myArrayCollection:ArrayCollection = new ArrayCollection(
{id: 1, name: "a"}
{id: 2, name: "b"}
{id: 3, name: "c"}
{id: 4, name: "d"}
....
);
I want to get the Array "1,2,3,4....". Right now, I have to loop through the Collection and push each value to an Array. Since my Collection can get large, I want to avoid looping.
var myArray:Array /* of int */ = [];
for each (var item:Object in myArrayCollection)
{
myArray.push(item.id);
}
Does anyone have any suggestions?
Thanks.
-
According to the docs the ArrayCollection does not keep the keys separate from the values. They are stored as objects in an underlying array. I don't think there is any way to avoid looping over them to extract just the keys since you need to look at every object in the underlying array.
Matt Dillard : While it's true that each object must be examined, an explicit loop is not necessary. The Array class offers convenience methods to help situations like this.tvanfosson : The loop just has a different author. Still it's best to use the framework provided mechanism absent some other reason. -
Once you get the underlying
Arrayobject from theArrayCollectionusing thesourceproperty, you can make use of themapmethod on theArray.Your code will look something like this:
private function getElementIdArray():Array { var arr:Array = myArrayCollection.source; var ids:Array = arr.map(getElementId); return ids; } private function getElementId(element:*, index:int, arr:Array):int { return element.id; }Eric Belair : This is exactly what I was looking for. Thank you so much!tvanfosson : This doesn't avoid looping, just avoids you writing the loop.
0 comments:
Post a Comment