views:

323

answers:

3

Im trying to extend flex ArrayCollection to be able to search for an object containing specific data and give it back.

Here is my function:

public function getItemContaining(value: String): Object {                      
          //Loop through the collection         
          for each(var i: Object in this) {                             
            //Loop through fields                               
            for(var j: String in i) {                   
                //If field value is equal to input value
                if(i[j] == value) {
                    return i;

                }
            }
        }
    //If not found
    return null;
    }

Problem is j is always null so the second loop never works. So i read felx loop descriptions and actually it should work just fine. What can possibly be the problem?

A: 

Try it like this:

for (var name:String in myObject){
  trace(name + ":" + myObject[name];
}

Okay that was actually the same you were doing. The error must be in this line:

for each(var i: Object in this) {

Try using this:

for each(var i: Object in this.source) {
Thomas
Is this different from the syntax in the question?
Michael Brewer-Davis
No, you're right! Will edit my answer.
Thomas
A: 

My first instinct would be to have a look at data type. You're setting up a loop declaring j:String and the symptom is that j is always null. This suggests to me that Flex is failing to interpret the elements of i as strings. If Flex only recognizes the elements of i as Objects (because all Strings are Objects, and Objects are the lowest common denominator), it would return null for j:String.

Try this for your inner loop:

for(var j: Object in i) {                   
    //If field value is equal to input value
    if(i[j] is String && (i[j] as String) == value) {
        return i;
    }
}
Eric Kolb
A: 

if you are using ArrayCollection as your datasource, you should look at using the IViewCursor interface. You can supply a custom compare function, or supply the fields top compare to. This interface is well documented with examples in adobe/livedocs

var _cursor:IViewCursor;
var _idSortField:SortField;
var _idSort:Sort = new Sort();
_idSortField = new SortField();
_idSortField.compareFunction = this.myCompareFunction; 
_idSort.fields = [_idSortField];
myArrayCollection.sort = _idSort;
myArrayCollection.refresh();
_cursor = myArrayCollection.createCursor();
if (_cursor.findAny(search))
   return _cursor;

if you are search for a value in a specific property, then its even easier. Here's the link to adobe livedocs on this topic

jcsf