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?
我有一个包含任意数量对象的Array Collection。我知道每个Object都有一个给定的属性。是否有一种简单的(也称为“内置”)方法来获取集合中该属性的所有值的数组?
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.
我想得到数组“1,2,3,4 ....”。现在,我必须遍历Collection并将每个值推送到Array。由于我的Collection可以变大,我想避免循环。
var myArray:Array /* of int */ = [];
for each (var item:Object in myArrayCollection)
{
myArray.push(item.id);
}
Does anyone have any suggestions?
有没有人有什么建议?
Thanks.
2 个解决方案
#1
2
Once you get the underlying Array
object from the ArrayCollection
using the source
property, you can make use of the map
method on the Array
.
使用source属性从ArrayCollection获取基础Array对象后,可以使用Array上的map方法。
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;
}
#2
2
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.
根据文档,ArrayCollection不会将键与值分开。它们作为对象存储在底层数组中。我不认为有任何方法可以避免循环它们只提取键,因为你需要查看底层数组中的每个对象。
#1
2
Once you get the underlying Array
object from the ArrayCollection
using the source
property, you can make use of the map
method on the Array
.
使用source属性从ArrayCollection获取基础Array对象后,可以使用Array上的map方法。
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;
}
#2
2
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.
根据文档,ArrayCollection不会将键与值分开。它们作为对象存储在底层数组中。我不认为有任何方法可以避免循环它们只提取键,因为你需要查看底层数组中的每个对象。