Skip to main content
Participant
September 25, 2011
Question

How to find an ArrayCollection item with a specific property value in flex4

  • September 25, 2011
  • 2 replies
  • 12191 views

Hi all,

private var collection:ArrayCollection = new ArrayCollection([

                                        {id:"1", stuff:"whatever1"},

                                        {id:"2", stuff:"whatever2"},

                                        {id:"3", stuff:"whatever3"}

  {id:"4", stuff:"whatever4"},

  {id:"5", stuff:"whatever5"},

  {id:"6", stuff:"whatever6"}

                              ]);

i have id=2 of specific property value  now i need to find item

    This topic has been closed for replies.

    2 replies

    Participating Frequently
    September 26, 2011

    Hi,

    ArrayCollection (and similar classes) already have builtin filtering fetaures, consider below sampel based on your collection:

    var collection:ArrayCollection = new ArrayCollection([

              {id:"1", stuff:"whatever1"},

              {id:"2", stuff:"whatever2"},

              {id:"3", stuff:"whatever3"},

              {id:"4", stuff:"whatever4"},

              {id:"5", stuff:"whatever5"},

              {id:"6", stuff:"whatever6"}

    ]);

    var findByIdFilter:Function = function(item:Object):Boolean

    {

              if(item.id == 2) return true;

              return false;

    };

    collection.filterFunction = findByIdFilter;

    collection.refresh();

    trace(collection);

    (you could write more advanced "findByFilter" function of course)

    it should trace:

    (Array)#0

      [0] (Object)#1

        id = "2"

        stuff = "whatever2"

    see docs:

    http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/collections/ListCollectionView.html#filterFunction

    and e.g.:

    http://weblog.mrinalwadhwa.com/2007/07/07/flex-tip-of-the-day-filterfunction-for-real-time-filtering-of-data/

    hth,

    regards,

    Peter

    Participant
    February 28, 2012
    Participant
    September 25, 2011

    Use a method like this which will return the first object which matches the conditions:

    private function findObjectByAttribute(arrayCollection:ArrayCollection,

                                                          attributeName:String, value:String):Object{

      for each (var object:Object in arrayCollection) {

                          if(object[attributeName]==value){

                                return object;

                          }

                    }

      return null;

    }

    To find the object with id=2, you would call the above method like this:

    var object:Object = findObjectByAttribute(collection, "id", "2");

    I hope this helps.

    -Mike

    ramblingdeveloper.com