AS3过滤器对象数组

时间:2011-05-11 13:38:26

标签: arrays flash actionscript-3

我有一个对象数组,我想根据一些搜索字符串进行过滤。我想从我的原始数组创建一个新数组,该数组只包含具有与搜索中的字符串相同属性的对象:

    var _array =  new Array();
    _array.push({name:"Ben",Title:"Mr",location:"UK"});
    _array.push({name:"Brian",Title:"Mr",location:"USA"});
    _array.push({name:"Ben",Title:"Mr",location:"USA"});

    var searchQuery:Array = new Array();
    searchQuery.push("Ben");
    searchQuery.push("Mr");

我希望新数组包含第一个和最后一个Object,因为它们都包含字符串“Ben”和“Mr”。

我可以使用Array.filter来实现这一目标吗?

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:3)

这是我的方法:

var _array:Array =  new Array();
_array.push({name:"Ben",Title:"Mr",location:"UK"});
_array.push({name:"Brian",Title:"Mr",location:"USA"});
_array.push({name:"Ben",Title:"Mr",location:"USA"});

var searchQuery:Array = new Array();
searchQuery.push("Ben");
searchQuery.push("Mr");

var resultArray:Array = _array.filter(ff); //The result.

function ff(el:*,ind:int,arr:Array){//Filter Function
    for(var i:int=0;i<searchQuery.length;i++){//Everything in searchQuery array should in el object.
        var b:Boolean = false;
        for(var s:String in el){
            if(el[s]==searchQuery[i]){
                b=true; break;
            }
        }
        if(!b) return false; //no searchQuery[i] in el... :(
    }
    return true;
}

答案 1 :(得分:2)

啊,没有什么比旧的收藏问题好了:))

虽然JiminP的答案确实是正确的;它有一些性能问题;其中最大的是closures in AS3 are slow,所以如果你在大型数组上搜索,那么操作可能会很慢。

以下功能不是很干净,但在大型阵列上会有更好的性能。

var _array : Array = [];
_array.push({name:"Ben", Title:"Mr", location:"UK"});
_array.push({name:"Brian", Title:"Mr", location:"USA"});
_array.push({name:"Ben", Title:"Mr", location:"USA"});

// I presumed you would want a little bit more control over the search matching; by
// using a Map you can ensure that no-one with the (somewhat unlikley) name of "Mr"
// gets matched by mistake.
var searchQueryMap : Dictionary = new Dictionary();
searchQueryMap["name"] = "Ben";
searchQueryMap["Title"] = "Mr";

const results : Array = [];

// Loop over earch objectin the 'haystack' that we wish to search.
for each (var object : Object in _array) 
{
    // This variable is used to break out of the loop if the current object doesn't match the
    // searchQueryMap; this gets reset to true for each loop of the supplied array.
    var match : Boolean = true;

    // Loop over each key (property) in the searchQueryMap.
    for (var key : * in searchQueryMap) 
    {
        if (searchQueryMap[key] !== object[key]) 
        {
            // No match, we can break out of looping over the searchQueryMap here.
            match = false;
            break;          
        }
    }

    // Check to see if we still have a positive match; if we do, push it onto the results Array.
    if (match) {
        results.push(object);   
    }
}

// Debug the results.
trace("Matches:");
for each (var result : Object in results)
{
    for (var prop : * in result) {
        trace("\t" + prop + " => " + result[prop]);
    }
    trace("---");
}