Get Object nested property using dot separated string

本小妞迷上赌 提交于 2021-01-28 14:24:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!