如何正确使用递归函数来遍历多个嵌套对象

时间:2016-03-17 19:53:05

标签: javascript angularjs recursion

在我的Angular应用程序中,我使用AngularTree指令(http://wix.github.io/angular-tree-control)呈现以下数据结构的树视图,如https://jsfiddle.net/eugene_goldberg/Lvwxx629/17/所示:

$scope.subjectAreas = [
        {
            name:   "Area-1",
            link:   "dashboards.dashboard_1",
            entities: [
                {
                    name: "entity 1"
                },
                {
                    name: "entity 2"
                }
            ],
            offerings: [
                {
                    name: "offering 1"
                },
                {
                    name: "offering 2"
                }
            ]
        },
        {
            name:   "Area-2",
            link:   "dashboards.dashboard_1",
            entities: [
                {
                    name: "entity 3"
                }
            ],
            offerings: [
                {
                    name: "offering 3"
                }
            ]
        },
        {
            name:   "Area-3",
            link:   "dashboards.dashboard_1",
            entities: [
                {
                    name: "entity 4"
                },
                {
                    name: "entity 5"
                },
                {
                    name: "entity 6"
                }
            ],
            offerings: [
                {
                    name: "offering 4"
                },
                {
                    name: "offering 5"
                }
            ]
        }
    ];

这个treeView指令提供了" createSubTree"功能,我使用如下:

function createSubTree(ary) {
        var res = [];
        if (ary) {
            res = ary.map(function(v, k) {
                var id = k + 1;
                return {
                    i: id,
                    id: 'id' + id,
                    label: v.name,
                    children: createSubTree(v.entities)
                }
            });

        }
        return res;
    }

    $scope.treedata = createSubTree($scope.subjectAreas);

输出如下:

Area-1
   entity-1
   entity-2
Area-2
   entity-3
Area-3
   entity-4
   entity-5
   entity-6

由于我的数据结构包含每个SubjectArea(实体和产品)的两个嵌套数组,我需要有一个实体子文件夹和一个子文件夹作为每个SubjectArea的子项,因此输出应该看起来像这样:

Area-1
   entities
       entity-1
       entity-2
   offerings
       offering-1
       offering-2
Area-2
   entities   
       entity-3
   offerings
       offering-3
Area-3
   entities
       entity-4
       entity-5
       entity-6
   offerings
       offering-4
       offering-5

如何修改当前代码以使递归函数为实体和产品创建子组?

1 个答案:

答案 0 :(得分:1)

将您的数据更改为:

$bob = ''; // set it
foreach($row as $image) {
   // append to it
   $bob .= '<div id=""><img src="" /></div>'.PHP_EOL;
}

print $bob;

我只完成了第一部分,但你可以完成其余部分。