如何正确使用递归函数经过多个嵌套对象 [英] how to properly use recursive function to go through multiple nested objects
问题描述
在我的角度应用程序,我使用AngularTree指令( HTTP://wix.github。 IO /角树控制)来呈现以下数据结构的树状视图,如图的 https://jsfiddle.net/eugene_goldberg/Lvwxx629/17/ :
In my Angular app, I'm using AngularTree directive (http://wix.github.io/angular-tree-control) to render a tree view of the following data structure, as shown in 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功能,我使用的如下:
This treeView directive provides the "createSubTree" function, which I'm using as follows:
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);
输出看起来是这样的:
The output looks like this:
Area-1
entity-1
entity-2
Area-2
entity-3
Area-3
entity-4
entity-5
entity-6
由于我的数据结构包含每个SubjectArea两个嵌套阵列(实体和产品),我需要有一个子文件夹的实体,并为产品的每个SubjectArea子女的子文件夹,所以输出应该像这样的:
As my data structure contains two nested arrays for each SubjectArea (entities, and offerings), I need to have a sub-folder for entities, and a sub-folder for offerings as children of each SubjectArea, so the output should look like this:
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
我如何修改当前code有递归函数创建子组的两个实体和产品?
How can I modify the current code to have the recursive function create sub-groups for both entities and offerings?
推荐答案
更改您的数据是:
$scope.subjectAreas = [{
name: "Area-1",
link: "dashboards.dashboard_1",
entities: [{
name: 'entities',
entities: [{
name: "entity 1"
}, {
name: "entity 2"
}]
}, {
name: 'offerings',
entities: [{
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"
}]
}];
我只完成了第一部分,但你可以完成其余部分。
I've only done the first part, but you can complete the rest.
这篇关于如何正确使用递归函数经过多个嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!