Add Dynamic Properties from String List
I have the following problem in AS3. I have a string like this one: "prop1:val1,prop2:val2,..."; I want to split and parse the string to obtain a dynamic object like this one: {prop开发者_开发问答1:"val1", prop2:"val2"}.
The simple way to solve it is to cycle through the string values and to do:
if (strProp1 == "prop1") o.prop1 = strVal1; if (strProp1 == "prop2") o.prop1 = strVal2;
Since I know the property names I expect, this works for me, but doesn't seem to be an elegant solution. I'm wondering if there is another way in as3 (similar to the reflection api in java), to solve this.
A quick example using split , a new Object :
// 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
//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];
}
精彩评论