2011-05-11 94 views
0

我有一個對象數組,我想根據某些搜索字符串進行過濾。我想創建從我原來的數組的新陣列將僅包含具有搜索等於字符串屬性的對象:對象的AS3過濾器陣列

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"); 

我希望新的數組來包含第一個和最後一個對象,因爲它們都包含字符串「Ben」和「Mr」。

我可以使用Array.filter來實現嗎?

任何幫助表示讚賞。

回答

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("---"); 
} 
+0

非常感謝! – redHouse71 2011-05-12 07:55:56

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; 
}