开发者

Is it possible to easily make an indexed array associative in actionscript?

I have a multidimentional array already made, brought in from a CSV file via csvlib

I also have the headers in an array and I would like a way to assign this array as the keys for the arrays.

here's a simplification

have a data array like so

data[0] -> [0] blue, [1] 1984, [2] wednesday [1] -> [0] green, [1] 1926, [2] friday

and a simple array of keys/properties (header array) like so:

[0] c开发者_开发技巧olour, [1] year, [2] weekday

I'd like to insert the keys to make data[0] -> [colour] blue, [year] 1984, [weekday] wednesday [1] -> [colour] green, [year] 1926, [weekday] friday

i've read up into associative arrays a bit and am not getting how to do this. (there's 38 properties so remember which is which in a straight indexed array is going to be quite inconvenient)


Well, you just want your second-level array to be a simple object instead. Let me show you some code:

var data:Array = [];

var record1:Object = {"colour": "blue", "year": "1984", "weekday": "wednesday"};
var record2:Object = {"colour": "green", "year": "1926", "weekday": "friday"};

data.push(record1);
data.push(record2);

trace("record 1:", data[0]["colour"], data[0]["year"], data[0]["weekday"]);
trace("record 2:", data[1]["colour"], data[1]["year"], data[1]["weekday"]);

Output:

record 1: blue 1984 wednesday
record 2: green 1926 friday

So I would convert the data array into the structure you want, something like this:

for (var i:int = 0; i < data.length; i++) {
  var record:Array = data[i];
  var newRecord:Object = {};

  for (var index:int in record)
    newRecord[headers[index]] = record[index];  

  data[i] = newRecord;
}

Now your data array is an array of associative arrays.


I assume your CSV uses ; as field separator, you read the CSV using URLLoader, and loading completes successfully.

In your completeHandler, you will now call csvToArray(loader.data as String);.

private function csvToArray ( data : String ) : Array
{
    var lines : Array = data.split ( /\R/ );
    var keyArray : Array = lines.splice ( 0, 1 )[0].split ( ";" );
    var assocArray : Array = [];
    for each (var line:String in lines)
    {
        var valArray : Array = line.split ( ";" );
        var assoc : Object = {};
        for (var i : int = 0; i < keyArray.length; i++)
        {
            var key : String = keyArray[i];
            if (key != null && key != "") assoc[key] = valArray[i];
        }
        assocArray.push ( assoc );
    }
    return assocArray;
}

Here's what happens:

  1. Read CSV's first line into keyArray
  2. Read each remaining line into valArray
  3. Use both to populate assocArray
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜