Sara Sara -4 years ago 102
Javascript Question

JavaScript - recursive looping through object

I'm trying to make a simple ACL just for practice.

I want to loop through my object data and if my currentViewer has a parent I want to add his path (access in my object) to arrayAccess.

So if my viewer is user his accessArray should be

["", home]
, if he's admin it would be
["", home, user]
and if he's a guest it will be only
[""]
.

How to do it in a recursive way, so I don't have to create thousands of for loops?

I was trying calling a
checkParent()
inside my
checkParent()
, but it only makes my loop infinitive. I'm sorry if it's a silly question, I'm very beginning in JS.



var currentViewer = "user";
var data = {
users: [{
role: "guest",
access: ""
},
{
role: "user",
access: "home",
parent: "guest"
},
{
role: "admin",
access: "user",
parent: "user"
}
]
};

var accessArray = [];

function checkRole() {
var users = data.users;
for (var i = 0; i < users.length; i++) {
if (currentViewer === users[i].role) {
accessArray.push(users[i].access);
console.log(accessArray);

function checkParent() {
if (users[i].parent) {
for (var j = 0; j < users.length; j++) {
if (users[i].parent === users[j].role) {
accessArray.push(users[j].access);
console.log(accessArray);
}
}
}
};
checkParent();
}
};
};
checkRole();




Answer Source

I don't think "recursiveness" should be a goal on its own... Why not create a Map of roles and their properties and use the parent property to retrieve a new item from this map, until you can't?

var data = {
  users: [{
      role: "guest",
      access: ""
    },
    {
      role: "user",
      access: "home",
      parent: "guest"
    },
    {
      role: "admin",
      access: "user",
      parent: "user"
    }
  ]
};

var roles = new Map(data.users.map(u => [u.role, u]));

var getAccess = function(role) {
  var access = [];
  var current = roles.get(role);

  while (current) {
    access.push(current.access);
    current = roles.get(current.parent);
  }

  return access.reverse();
}

console.log("guest", getAccess("guest"))
console.log("user", getAccess("user"))
console.log("admin", getAccess("admin"))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download