您可以使用filter()和map()來創建所需數據的新數組。
讓我們假設你已經得到JSON數據到的ArrayCollection(或陣列),所以在這個例子中,我只是創建陣列:
private var GetVotesResult:Array = [{"Aid":0,"Arank":0,"Atext":null,"ClientId":16,"Votes":0,"qid":10,"qtext":"Who will win 2011 football world cup?"},
{"Aid":4,"Arank":1,"Atext":"yes","ClientId":null,"Votes":0,"qid":null,"qtext":"Who stole my socks?"},
{"Aid":5,"Arank":2,"Atext":"no","ClientId":null,"Votes":0,"qid":null,"qtext":null},
{"Aid":6,"Arank":3,"Atext":"i don't know","ClientId":null,"Votes":0,"qid":null,"qtext":null}];
現在你可以使用Array.filter創建一個新的數組,只有包含具有所希望的領域的有效值元素:
//Get an array with elements that have the desired property:
public function getElementsWithProperty(propName:String):Array {
return GetVotesResult.filter(elementHasProp(propName));
}
private function elementHasProp(propName:String):Function {
return function(element:Object, index:int, array:Array):Boolean {
return (element[ propName ] != null);
}
}
爲了檢驗上述:
var elementsWithQText:Array = getElementsWithProperty('qtext');
trace('Values of qtext in elementsWithQText array: ');
for each (var element:Object in elementsWithQText) {
trace(element.qtext);
}
//OUTPUT:
//Values of qtext in elementsWithQText array:
//Who will win 2011 football world cup?
//Who stole my socks?
或者,你可以使用Array.map爲某個屬性創建唯一值的數組:
//Get an array of only a certain property:
public function makeArrayOfProperty(propName:String):Array {
return GetVotesResult.map(valueOfProp(propName));
}
private function valueOfProp(propName:String):Function {
return function(element:Object, index:int, array:Array):String {
return element[ propName ];
}
}
您可以測試上面的地圖功能:
var valuesOfAtext:Array = makeArrayOfProperty('Atext');
trace('Values of valuesOfAtext: ' + valuesOfAtext);
//OUTPUT: Values of valuesOfAtext: ,yes,no,i don't know
本頁面做了偉大的作業描述地圖,過濾器和其他Array:http://www.onebyonedesign.com/tutorials/array_methods/
雖然Array.filter,Array.map和其他函數Array/Vector方法是非常好吃的,並允許一些不錯的鏈式方法調用 - 它們確實運行得很不錯比他們的mo慢一點基於傳統的基於循環的對應物。 – JonnyReeves 2012-01-19 22:17:13