如何创建类似 sql 的 AS3 ArrayCollection 分组



我有一个动态创建的arrayCollection,就像底部一样:

arrCol = ({"ID":ids[i][0], "Price":ids[i][1], "OtherInfo":ids[i][2]});

我想对数据进行分组并按 ID 汇总Price

如果这个ArrayCollection是一个SQL表,我可以使用这样的查询:

SELECT ID, SUM(Price), OtherInfo 
FROM TableA 
GROUP BY ID

那么,如何像SQL中的查询示例一样设置AS3函数,或者是否有任何本机ArrayCollection类呢?

试试这个,没有内置函数可以满足您的需求(总和,分组),所以我们需要手动完成以下代码将为您提供帮助。

var arrCol:ArrayCollection = new ArrayCollection();
arrCol.addItem({"ID":1, "Price":100, "OtherInfo":"info"});
arrCol.addItem({"ID":1, "Price":700, "OtherInfo":"info"});
arrCol.addItem({"ID":2, "Price":100, "OtherInfo":"info"});
arrCol.addItem({"ID":2, "Price":200, "OtherInfo":"info"});
arrCol.addItem({"ID":3, "Price":100, "OtherInfo":"info"});
arrCol.addItem({"ID":3, "Price":400, "OtherInfo":"info"});
arrCol.addItem({"ID":3, "Price":100, "OtherInfo":"info"});
var dic:Dictionary = new Dictionary();
for each (var item:Object in arrCol) 
{
    if(!dic[item.ID]){
        dic[item.ID] = item;
    }
    else{                        
        var oldSumObj:Object = dic[item.ID];
        oldSumObj.Price +=item.Price;
        dic[item.ID] = oldSumObj;
    }
}
var groupedList:ArrayCollection = new ArrayCollection();
for each (var itemObj:Object in dic) 
{
    groupedList.addItem(itemObj);
}   

输出将为:

"groupedList"   mx.collections.ArrayCollection (@27af939)   
    [0] Object (@8836569)   
        ID  1   
        OtherInfo   "info"  
        Price   800 [0x320] 
    [1] Object (@87a7c71)   
        ID  2   
        OtherInfo   "info"  
        Price   300 [0x12c] 
    [2] Object (@87a7bc9)   
        ID  3   
        OtherInfo   "info"  
        Price   600 [0x258] 

虽然无法在 AS3 中进行 SQL 类型查询,但可以使用其一系列方法来获得相同的结果。

// Work with an array.  Child elements must be an associative array (structure/object/hash-table)
var ac:Array = [
    {"name":"apple", "price":100, "color":"red"},
    {"name":"banana", "price":50, "color":"yellow"},
    {"name":"pear", "price":250, "color":"green"},
]
// Apply the order your want based on the property you're concerned with.
ac.sortOn("price", Array.ASCENDING)
// If necessary, create a subset of that array with the "select"-ed columns.
var output:Array = [];
for each (var entry:Object in ac) {
    output.push({entry.name, entry.color});
}
// Printing output will result in
// 0:{"name":"banana", "color":"yellow"},
// 1:{"name":"apple", "color":"red"},
// 2:{"name":"pear", "color":"green"}

相关内容

  • 没有找到相关文章

最新更新