'loop through object properties in flash

I have an object that gets properties added in this sequence.

Home
School
living
status
sound
Memory

When I loop through the object they don't come out in that sequence. How do I get them to come out in this order.

data is the object

for (var i:String in data)
{
    trace(i + ": " + data[i]);
}

Is there a way to sort it maybe?



Solution 1:[1]

The only way to sort the order that you can access properties is manually. Here is a function I have created for you to do just that:

function getSortedPairs(object:Object):Array
{
    var sorted:Array = [];

    for(var i:String in object)
    {
        sorted.push({ key: i, value: object[i] });
    }

    sorted.sortOn("key");

    return sorted;
}

Trial:

var test:Object = { a: 1, b: 2, c: 3, d: 4, e: 5 };
var sorted:Array = getSortedPairs(test);

for each(var i:Object in sorted)
{
    trace(i.key, i.value);
}

Solution 2:[2]

The link Marty shared explains what is happening pretty well and his answer is excellent too.

Another solution you might also consider if order matters is to use a Vector.

// Init the vector
var hectorTheVector:Vector.<String> = new Vector.<String>();

// Can add items by index
hectorTheVector[0] = "Home";
hectorTheVector[1] = "School";
hectorTheVector[2] = "living";

// Or add items by push
hectorTheVector.push("status");
hectorTheVector.push("sound");
hectorTheVector.push("Memory");

//See all items in order
for(var i:int = 0; i < hectorTheVector.length; i++){
    trace(hectorTheVector[i]);
}

/* Traces out:
Home
School
living
status
sound
Memory
*/

An Array would also preserve order. here is a good topic on sorting Arrays

Solution 3:[3]

ActionScript 3, you can decode JSON string into Object through this function

function createJSONObjectFromString(data: String):Object {
        var obj: Object = new Object();
        data = data.replace("{", "");
        data = data.replace("}", "");
        var data_array = [];
        if (data != ""){
            if (data.indexOf(",")){
                while (data.indexOf(", ") >= 0){
                    data = data.replace(", ", ",");
                }
                data_array = data.split(",");
            }else{
                data_array = [data];
            }
        }
        for (var i = 0; i < data_array.length; i++){
            var prop_val = data_array[i].split(":");
            obj[removeSlashes(prop_val[0])] = removeSlashes(prop_val[1]);
        }
        return obj;
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ToddBFisher
Solution 3 Musanss