Converting an array of String objects to an array of Object objects in Flex

by Peter deHaan on March 26, 2008

in List

The following example shows how you can convert an array of strings to an array of objects so it can be used as a data provider in Flex.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/03/26/converting-an-array-of-string-objects-to-an-array-of-object-objects-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            private var arrayOfString:Array;
            private var arrayOfObject:Array;

            private function init():void {
                arrayOfString = ["test", "test", "fork", "test"];
                arrayOfObject = stringArrayToObjectArray(arrayOfString);
            }

            private function stringArrayToObjectArray(sourceArray:Array, key:String = "label"):Array {
                var returnArray:Array = new Array();
                var idx:uint;
                var len:uint = sourceArray.length;
                for (idx=0; idx<len; idx++) {
                    var obj:Object = {};
                    obj[key] = sourceArray[idx];
                    returnArray.push(obj);
                }
                return returnArray;
            }
        ]]>
    </mx:Script>

    <mx:ApplicationControlBar dock="true">
        <mx:Button label="Array of String"
                    click="list.dataProvider = arrayOfString;" />
        <mx:Button label="Array of Object"
                    click="list.dataProvider = arrayOfObject;" />
    </mx:ApplicationControlBar>

    <mx:List id="list"
            width="100"
            rowCount="6"
            initialize="init();" />

</mx:Application>

View source is enabled in the following example.

A reader, Chetan, commented and suggested another (and admittedly much better) approach, using the Array.map() method.

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/03/26/converting-an-array-of-string-objects-to-an-array-of-object-objects-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            private var arrayOfString:Array;
            private var arrayOfObject:Array;

            private function init():void {
                arrayOfString = ["test", "test", "fork", "test"];
                arrayOfObject = arrayOfString.map(toObject);
            }

            private function toObject(element:String, index:int, arr:Array):Object {
                return {label: element};
            }
        ]]>
    </mx:Script>

    <mx:ApplicationControlBar dock="true">
        <mx:Button label="Array of String"
                    click="list.dataProvider = arrayOfString;" />
        <mx:Button label="Array of Object"
                    click="list.dataProvider = arrayOfObject;" />
    </mx:ApplicationControlBar>

    <mx:List id="list"
            width="100"
            rowCount="6"
            initialize="init();" />

</mx:Application>

For those of you unfamiliar with the Array class’s map() method, it is one of the many new Array methods in ActionScript 3.0. Other new methods include: every(), filter(), forEach(), map(), and some(). For more information, check out the Flex 3 documentation’s Array class in the Flex 3 Language Reference.

{ 3 comments… read them below or add one }

1 Chetan March 28, 2008 at 7:07 am

Suggestion: You can also use Array.map() instead of looping to make it (slightly) more readable.

Reply

2 peterd March 28, 2008 at 7:18 am

Chetan,

Fantastic suggestion! I never even thought about trying that. I’ll update the article with the new (and better) technique.

But in the meantime, here is my revised <mx:Script /> block, snippet style:

private var arrayOfString:Array;
private var arrayOfObject:Array;

private function init():void {
    arrayOfString = ["test", "test", "fork", "test"];
    arrayOfObject = arrayOfString.map(toObject);
}

private function toObject(element:String, index:int, arr:Array):Object {
    return {label: element};
}

Again, huge thanks!

Peter

Reply

3 Visi April 8, 2008 at 12:05 am

Greate,
I really appreiciate the Peter work and Chetan suggetion of improvement in the code snippet.
I have a query in this respect. I am getting data in following format. How can I display the select box using the arrVisibility array and selected option value using Visibility element value. And also how can I display he other objects value like obj_UsersVO] => stdClass Object and [obj_CommonVO] => stdClass Object in the data grid.
Can you please help me as I am new to flex.

[0] => FeedbackVO Object
(
[IdFeedback] => 1
[FeedbackType] => A
[TrackId] => 1
[Rating] => 1
[Visibility] => V
[CreatedOn] => 2008-01-01 00:00:00
[CreatedBy] => 35
[Comments] => 1111
[UserId] => 1
[arrVisibility] => Array
(
[V] => Visible
[H] => Hidden
[F] => Featured
)

[TrackTitle] => junoon1111
[obj_UsersVO] => stdClass Object
(
[firstname] => Scott
[lastname] => Tiger
)

[obj_CommonVO] => stdClass Object
(
[UserName] => Tiger Scott
[Play] => Yes
)

)

[1] => FeedbackVO Object
(
[IdFeedback] => 2
[FeedbackType] => A
[TrackId] => 1
[PromoId] => 1
[Rating] => 1
[Supporting] => Y
[Visibility] => V
[CreatedOn] => 2008-01-01 00:00:00
[CreatedBy] => 35
[Comments] => 2222
[UpdatedOn] => 2008-01-01 00:00:00
[UpdatedBy] => 2
[UserId] => 2
[FeedbackArray] =>
[userRecord] =>
[commonRecord] =>
[arrVisibility] => Array
(
[V] => Visible
[H] => Hidden
[F] => Featured
)

[TrackTitle] => junoon1111
[obj_UsersVO] => stdClass Object
(
[firstname] => Blake
[lastname] => Addison
)

[obj_CommonVO] => stdClass Object
(
[UserName] => Addison Blake
[Play] => No
)

)

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: