开发者

Converting nested ArrayCollection elements to another class

I have an ArrayCollection and each element is an instance of the TreeNode class (a custom class made by me) that has a "children" property which is an ArrayCollection of more TreeNode elements. That way, I have a t开发者_运维百科ree of elements in an ArrayCollection structure:

tree = new ArrayCollection([
    [new TreeNode(param1, param2, new ArrayCollection([
        [new TreeNode(param1, param2, null)],
        [new TreeNode(param1, param2, new ArrayCollection([
            [new TreeNode(param1, param2, null)],
            [new TreeNode(param1, param2, new ArrayCollection([
                [new TreeNode(param1, param2, null)],
                [new TreeNode(param1, param2, null)]
            ]))],
            [new TreeNode(param1, param2, new ArrayCollection([
                [new TreeNode(param1, param2, null)],
                [new TreeNode(param1, param2, null)]
            ]))]
        ]))]
    ]))],
    [new TreeNode(param1, param2, null)]
]);

The TreeNode constructor has 3 parameters: The first two don't matter now but the third is the children property (an ArrayCollection) and if the TreeNode doesn't have any children, then that parameter must be set to null.

I wrote the following function to parse the "tree" structure recursively:

private function parse(obj:Object):void {
    for (var i:int = 0; i < obj.length; i++) {
        if (obj[i] is TreeNode) {
            if (obj[i].children != null) {
                parse(obj[i].children);
            }
        } else {
            parse(obj[i]);
        }
    }
}
parse(tree);

But my problem is: I need to have the same "tree" structure (it doens't need to be the same variable) filled with instances of another class. How can I achieve that?


I did it:

private function parse(obj:Object, ancestor:Node):void {
    for (var i:int = 0; i < obj.length; i++) {
        if (obj[i] is TreeNode) {

            var node:Node = new Node(obj[i].param1, obj[i].param2);
            node.ancestor = ancestor;

            if (ancestor != null) {
                ancestor.children.push(node);
            }

            if (obj[i].children != null) {
                parse(obj[i].children, node);
            }

            obj[i] = node;
        } else {
            parse(obj[i], ancestor);
        }
    }
}
parse(tree, null);

That way, all the TreeNodes will be converted to Nodes (Node is another custom class I made)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜