从字符串列表中添加动态属性

时间:2011-01-01 13:12:36

标签: flex flash actionscript-3 dynamic object

我在AS3中遇到以下问题。我有一个像这样的字符串:“prop1:val1,prop2:val2,...”;我想拆分并解析字符串以获得像这样的动态对象:{prop1:“val1”,prop2:“val2”}。

解决它的简单方法是循环遍历字符串值并执行:

if(strProp1 ==“prop1”)o.prop1 = strVal1; if(strProp1 ==“prop2”)o.prop1 = strVal2;

因为我知道我期望的属性名称,这对我有用,但似乎不是一个优雅的解决方案。我想知道as3中是否有另一种方法(类似于java中的反射api)来解决这个问题。

2 个答案:

答案 0 :(得分:0)

 //get an Array of the values
 var strData:Array = yourString.split(",");

 //create the object you want to populate
 var object:Object = {};

 for( var i:int ; i < strData.length ; ++i )
 {
     //a substring containing property name & value
     var valueString:String = strData[i];

     var dataArray:Array = valueString.split(":");

     obj[dataArray[0]] = dataArray[1];
 }

答案 1 :(得分:0)

使用split的快速示例,一个新的对象:

// function that will parse the string an return an object with
// all field and value
function parse(str:String):Object {
 // create a new object that will hold the fields created dynamically
 var o:Object = {};

 // split the string from ',' character
 // this will return an array with string like propX:valX
 for each (var values:String in str.split(",")) {
  // now split the resulting string from ':' character
  // so you have an array with string propX and valX
  var keyvalue:Array = values.split(":");
  // assign the key/value to the object
  o[keyvalue[0]] = keyvalue[1];
 }
 return o;
}

// usage example
var str:String="prop1:val1,prop2:val2,prop3:val3";

var myObject:Object = parse(str);

trace(myObject.prop2); // output val2