Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 397
p-sara Avatar asked Jun 20 '26 18:06

p-sara


1 Answers

You can try this:

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

var currentUser = "admin";

var arr = [];//array that you need

var defineAccess = function(item){
    if(item.parent){
        var index = data.users.map(function(e) { return e.role; }).indexOf(item.parent);
        defineAccess(data.users[index]); //recursive calling
        arr.push(data.users[index].access);
    }
}

data.users.forEach(function(item){
    if(currentUser === item.role){
        arr.push(item.access);
        defineAccess(item);
    }   
})

console.log(arr); //final output array
like image 101
Rahul Arora Avatar answered Jun 23 '26 08:06

Rahul Arora