Justin
Justin

Reputation: 972

Loop through JS Object and function on each item

I must be over thinking the solution for this problem but can't seem to get this right.

I have an array object like so:

[ 
  {  ItemID: 1,  Path: '/Admin',     Name: 'Admin'   },
  {  ItemID: 2,  Path: '/Product',   Name: 'Product' },
  {  ItemID: 1,  Path: '/Reports',   Name: 'Reports' } 
]

I want to map over each item and for each one I need to run a function that will return whether they have access. i.e. a boolean (yes/no).

So far I have something like this:

const newData = data.map((curr, val , arr) => {

    if (checkAccess(username, curr.Name )) {  //checkAccess returns true or false
        return { ...current };
    }
});

I only want to return the ones they have access to.

so assuming that a user is unable to access Admin the final object should be:

[ 
  {  ItemID: 2,  Path: '/Product',   Name: 'Product' },
  {  ItemID: 1,  Path: '/Reports',   Name: 'Reports' } 
]

EDIT:

The issue is also that the function isn't returning a true / false

function checkInGroup(username, name) {
    let inGroup = "";
    ad.isUserMemberOf(username, name, function(err, isMember) {
        if (err) {
            return res.json("Error ", err);
        }
        inGroup = isMember; //this part returns true
    });
    return inGroup; //this seems to return empty string
}

Upvotes: 0

Views: 48

Answers (1)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100195

try using filter, as it creates a new array with all elements that pass the condition:

const res = data.filter(obj => obj.Path !== '/Admin');
console.log(res);

Upvotes: 4

Related Questions