In my angular , i am having one $scope variable as below.
$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" : [] }
]}
]}
]}
];
I want to first find array for given path
Admin>subAdmin2-1
and insert
{ "roleName" : "subAdmin2-1-3", "roleId" : "role1213", "children" : [] }
Please guide, how can achieve this.
This is quick and dirty but will work:
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]);
}
}
}
}
}
}
You can try improving with a recursion. And you probably want this to be in a function, so you can call
var role = "{ "roleName" : "subAdmin2-1-3", "roleId" : "role1213", "children" : [] }";
$scope.addSubRole(role, "Admin", "subAdmin2-1")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.