问题
Is there in Flex any utility to get object nested property using dot separated string like this:
SomeUtil.getObjectProperty(object, "child.property");
回答1:
You can roll your own, assuming object is a dynamic object :
public function getObjectProperty(object:Object, property:String):Object
{
var parts:Array = property.split(".");
if(parts && parts.length == 2 && object && object[parts[0]] && object[parts[0]][parts[1]])
{
return object[parts[0]][parts[1]];
}
return null;
}
Here is another one that will work with different strings :
private function test(e:Event = null):void
{
var obj:Object = {
"child": {
"property":1
},
"anotherproperty": 2
};
var test1:Object = getObjectProperty(obj, "anotherproperty");
var test2:Object = getObjectProperty(obj, "child.property");
}
public function getObjectProperty(object:Object, property:String):Object
{
var parts:Array = property.split(".");
var returnProp:Object = null;
for (var i:int = 0; i < parts.length; i++)
{
if(object[parts[i]])
{
returnProp = object[parts[i]];
object = returnProp;
}
else
return null;
}
return returnProp;
}
来源:https://stackoverflow.com/questions/17383300/get-object-nested-property-using-dot-separated-string