Angular.js如何在json数组中搜索给定路径

时间:2017-11-09 16:19:22

标签: javascript angularjs json

在我的角度,我有一个$ scope变量,如下所示。

$scope.roleList2 = [
        { "roleName" : "User", "roleId" : "role1", "children" : [
          { "roleName" : "subUser1", "roleId" : "role11", "collapsed" : true, "children" : [] },
          { "roleName" : "subUser2", "roleId" : "role12", "collapsed" : true, "children" : [
            { "roleName" : "subUser2-1", "roleId" : "role121", "children" : [
              { "roleName" : "subUser2-1-1", "roleId" : "role1211", "children" : [] },
              { "roleName" : "subUser2-1-2", "roleId" : "role1212", "children" : [] }
            ]}
          ]}
        ]},

        { "roleName" : "Admin", "roleId" : "role2", "children" : [
          { "roleName" : "subAdmin1", "roleId" : "role11", "collapsed" : true, "children" : [] },
          { "roleName" : "subAdmin2", "roleId" : "role12", "children" : [
            { "roleName" : "subAdmin2-1", "roleId" : "role121", "children" : [
              { "roleName" : "subAdmin2-1-1", "roleId" : "role1211", "children" : [] },
              { "roleName" : "subAdmin2-1-2", "roleId" : "role1212", "children" : [] }
            ]}
          ]}
        ]},

        { "roleName" : "Guest", "roleId" : "role3", "children" : [
          { "roleName" : "subGuest1", "roleId" : "role11", "children" : [] },
          { "roleName" : "subGuest2", "roleId" : "role12", "collapsed" : true, "children" : [
            { "roleName" : "Banned Area", "roleId" : "role121", "children" : [
              { "roleName" : "subGuest2-1-1", "roleId" : "role1211", "Parent":"Banned Area" ,"children" : [] },
              { "roleName" : "subGuest2-1-2", "roleId" : "role1212", "Parent":"Banned Area", "children" : [] }
            ]}
          ]}
        ]}
      ];

我想首先找到给定路径的数组

Admin>subAdmin2-1

并插入

{ "roleName" : "subAdmin2-1-3", "roleId" : "role1213", "children" : [] }

请指导,如何实现这一点。

1 个答案:

答案 0 :(得分:0)

这很快又脏,但可行:

for (var i=0; i<$scope.roleList2.length; i++) {
  if ($scope.roleList2[i].roleName == "Admin") {
    var subRoles = $scope.roleList2[i].children;
    for (var k=0; k<subRoles.length; k++) {
      if (subRoles[k].roleName == "subAdmin2") {
        var subSubRoles = subRoles[k].children;
        for (var j=0; j<subSubRoles.length; j++) {
          if (subSubRoles[j].roleName == "subAdmin2-1") {
            subSubRoles[j].children.push({ "roleName" : "subAdmin2-1-3", "roleId" : "role1213", "children" : [] });
            console.log(subSubRoles[j]);
          }
        }
      }
    }
  }
}

您可以尝试使用递归进行改进。你可能希望这是一个函数,所以你可以调用

var role = "{ "roleName" : "subAdmin2-1-3", "roleId" : "role1213", "children" : [] }";
$scope.addSubRole(role, "Admin", "subAdmin2-1")