Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find an ArrayCollection item with a specific property value?

I have some XML structures like this:

var struct:XML = <mh>
  <mi id="1" stuff="whatever"/>
  <mi id="2" stuff="whatever"/>
  <mi id="3" stuff="whatever"/>
</mh>;

I know I can access a subnode by "id", in this way:

var stuff:Object = struct.(hasOwnProperty('@id') && @id == '2').@stuff;

Now I have some similar ArrayCollection structure:

private var cmenu:ArrayCollection = new ArrayCollection([
    {id:"1", stuff:"whatever"},
    {id:"2", stuff:"whatever"},
    {id:"3", stuff:"whatever"}
]);

I wonder if items can be accessed in a similar way, like this:

var stuff:Object = cmenu['id == 2'].stuff;

Is it possible?

like image 512
Giorgio Gelardi Avatar asked Oct 14 '09 13:10

Giorgio Gelardi


1 Answers

You can generalize Matt's answer a bit so that you can pass in the ID value you want instead of hard-coding it, and only need a single line to get your match (I assume you may want to do this in multiple places).

First you'd write a function to generate your find function:

function findId(id:int):Function {
  return function( element : *, index : int, array : Array ) : Boolean
  {
    return element.id == id;
  }
}

Then I'd write a function to return the first match so you don't have to duplicate the two lines:

function findInCollection(c:ArrayCollection, find:Function):Object {
  var matches : Array = c.source.filter( find );
  return ( matches.length > 0 ? matches[0] : null );
}

Then you'd just do this:

var stuff:String = findInCollection(cmenu, findId(2)) as String;
like image 112
Herms Avatar answered Oct 25 '22 00:10

Herms