在ActionScript中从Object创建数组

时间:2011-07-31 12:11:36

标签: arrays actionscript-3 object

我有一个从JSON反序列化的对象。看起来像这样,在FlashBuilder中进行了内省:

Cities //object
   Denver //object, contained within Cities
       description "Mile High City"
       location "Colorado"
   Los Angeles//object, contained within Cities
       description "City of Angels"
       location "California"
   New York //object, contained within Cities
       description "The Big Apple"
       location "New York State"

我所要做的就是创建一系列城市,这样我就能做到这样的事情:      迹(arrCities [I] .DESCRIPTION); //根据i的值返回“Mile High City”或“City of Angels”。

但我无法理解。在我试过的事情中,没有一个能起作用:

var arrCities:Array = objCities as Array; //doesn't work

  for (var prop:String in objCities);       
  { 
     trace("objCities."+prop+" = "+objCities[prop]);
     trace(prop.description);  //this returns only one random description 
                              //(sometimes "The Big Apple, sometimes "City of Angels" etc.
     arrCities.push(objCities[prop]);

  }

  for each (var prop:String in objCities);      
  { 
     trace("objCities."+prop+" = "+objCities[prop]);
     trace(prop.description);  // returns "objCities.[object Object] = undefined"
     arrCities.push(objCities[prop]);

  }

必须有一个简单的解决方案,但我找不到它。任何帮助表示赞赏。

感谢。

cities: {
    denver: {
        dateCreated: 0
        description: "Mile High Cty"
        cityCode: "dv"
        cityName: "Denver"
        properties: { }
        title: ""
    }
    newyork: {
        dateCreated: 0
        description: "The Big Apple"
        cityCode: "nyc"
        cityName: "New York"
        properties: { }
        title: ""
    }
    losangeles: {
        dateCreated: 0
        description: "City of Angels"
        cityCode: "la"
        cityName: "Los Angeles"
        properties: { }
        title: ""
    }
}

2 个答案:

答案 0 :(得分:3)

var objCities:Object = JSON.decode(objStr);
var arrCities:Array = [];

for each (var prop:Object in objCities)     
{ 
     arrCities.push(prop);
}
trace(arrCities[0].description);

阐释:

表单for(var foo in bar)将foo设置为迭代中bar的当前元素的名称。 for each(var foo in bar)将foo设置为bar元素的属性。您希望每个内部对象(而不是该对象的名称)都插入到数组中,以便最终得到一组对象,如{description:"City of Angels",location:"California"}

答案 1 :(得分:0)

该库包含将JSON读入AS3对象的事实标准:https://github.com/mikechambers/as3corelib。你需要使用它。开发自己版本的JSON解析器(可能)无论如何都是合理的。