1

Flex 中是否有任何实用程序可以使用点分隔字符串获取对象嵌套属性,如下所示:

SomeUtil.getObjectProperty(object, "child.property");
4

1 回答 1

3

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;
}
于 2013-06-29T18:36:34.903 回答