Flex ArrayCollection Remove Items By Property Value

Posted: November 3, 2011 in Flex

You want to remove all rows in an ArrayCollection where the property (e.g. parentID) = the value (eg. 5). It basically searches the entire ArrayCollection and removes all rows that meet your criteria. I needed this because I wanted to delete all children of a specific parentID. So, I made a little function to make this easy to call for any use case based on what I learned from this post http://www.actionscript.org/forums/showthread.php3?t=156163 . The trick is to only increment i if the criteria is not a match, since Flex does change the index after each item is removed. Nice trick creyenders. Thanks!

Paying it forward with a Flex function to make it easy for Flex developers to use.

public function removeItemsByPropertyValue(ac:ArrayCollection, property:String, value:String):void
			{
				for( var i : uint = 0 ; i < ac.length ; null ){
					
					var obj:Object = Object(ac[i])
					if( obj[ property ] == value ){
						ac.removeItemAt( ac.getItemIndex( obj ) );
					}else{
						i++;
					}
				}
			}
Advertisements
Comments
  1. for( var i : uint = 0 ; i = 0; i– )
    note that one must use an “int” because the value will go negative. In fact, I always use “int” unless I need the range of a uint.

    var obj:Object = Object(ac[i])

    — I think the ac[index] defaults to an Object

    ac.removeItemAt( ac.getItemIndex( obj ) );

    — might this be ac.removeItemAt(i) ? You already have the index. Your code would work with “for each(…)”.

    Cheers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s