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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With