gpt4 book ai didi

javascript - AngularJS 和 JSON - 添加子对象

转载 作者:行者123 更新时间:2023-11-29 22:04:43 24 4
gpt4 key购买 nike

我正在使用 AngularJS 并且在我的 Controller 中。我有我的 $scope.tree 变量来保存一个简单的 JSON 对象。我正在尝试构建嵌套树,数据来自多个 rest 调用。

在我的第一个 REST 调用之后,我成功地拥有了我的初始 $scope.tree 对象:

[
{"name":"Item 1 Name","id":"1","parentid":"","children":[]},
{"name":"Item 2 Name","id":"2","parentid":"","children":[]}
]

我进行了第二次 REST 调用并返回了 2 个元素:

{"name":"Item 3 Name","id":"3","parentid":"2","children":[]},
{"name":"Item 4 Name","id":"4","parentid":"2","children":[]}

我想将这些作为适当的 child 添加到第一个电话中以结束:

[
{"name":"Item 1 Name","id":"1","children":[]},
{"name":"Item 2 Name","id":"2","children":[
{"name":"Item 3 Name","id":"3","parentid":"2","children":[]},
{"name":"Item 4 Name","id":"4","parentid":"2","children":[]}
]}
]

第三次调用:

{"name":"Item 5 Name","id":"5","parentid":"3","children":[]},
{"name":"Item 6 Name","id":"6","parentid":"4","children":[]}

最后是:

[
{"name":"Item 1 Name","id":"1","children":[]},
{"name":"Item 2 Name","id":"2","children":[
{"name":"Item 3 Name","id":"3","parentid":"2","children":[
{"name":"Item 5 Name","id":"5","parentid":"3","children":[]}
]},
{"name":"Item 4 Name","id":"4","parentid":"2","children":[
{"name":"Item 6 Name","id":"6","parentid":"4","children":[]}
]}
]}
]

在我的 Controller 中我有类似的东西:

$scope.tree = {};
$scope.restcall1 = (results of restcall)
$scope.restcall2 = (results of restcall)
$scope.restcall3 = (results of restcall)

$scope.tree = $scope.restcall1;

现在我需要加入 $scope.restcall1 和 $scope.restcall2,所以我使用 addCall2 方法构建了一个 treeBuilder 服务。

$scope.tree = treeBuilder.addBranch($scope.tree, $scope.$restcall1);

在 treeBuilder 服务中:

    addBranch: function(branch, tree){
for (var i=0; i<branch.length; i++){
network = _.filter(tree, function(obj){
if(obj.id == branch[i].parentId){
obj.children.push(branch[i]);
}
});
}
return tree;
},

obj.children.push(new_branch);不起作用,我尝试了其他 10 种方法 - 我发现父对象很好,但找不到将分支添加到 parent.children 的方法。正如您在上面看到的,如果有帮助,我可以使用下划线。

谢谢!

最佳答案

我对你想做的事情的基本理解是这样的:

var obj = {
children:[]
}
obj.children.push({test:'Hello world'});
console.log(obj.children);//[Object { test="Hello world"}]

我说的对吗?

关于javascript - AngularJS 和 JSON - 添加子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21651728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com