8

I have an array with permissions from Facebook and an array of the permissions that the user shouldve given:

window.FB.api('/me/permissions', function(perm){                     
    if(perm){
       var given_permissions =  _.keys(perm['data'][0];
       var needed_permissions = ["publish_stream", "email"];
       //now check if given permissions contains needed permissions
    }
}

Now I want to compare if all the needed_permissions are in given_permissions, in an underscore savvy way (without looping two arrays myself and compare values). I saw a _.include method, but this compares an array with a value. I want to return true if all the permissions are available and else a false. I was looking for a nice single line call if possible.

The reason for this is, that FB.login returns true even if the user chooses to cancel the extended permissions. So I need to doublecheck this.

3 Answers 3

18

You could use _.difference to see if removing the given permissions from your required permissions leaves anything behind:

var diff = _(needed_permissions).difference(given_permissions)
if(diff.length > 0)
    // Some permissions were not granted

A nice side effect of this is that you get the missing permissions in diff in case you want to tell them what's wrong.

Sign up to request clarification or add additional context in comments.

2 Comments

That's also a nice solution. I'll have to mark the other one as answer, because that's basicly what I asked for, but I think I'll use this solution so I can provide better feedback.
I disagree and think it would be much more useful to make this your accepted answer. _.difference is exactly what you asked for ("compare two arrays if keys match with underscore.js" - the rest was really speculation I think) and indeed the answer you "accepted" because you used it! Just a thought to help others looking at this. I guess not everyone will check past the accepted answer. The accepted answer is pretty poor as a solution since it adds nothing when underscore provides a function to do exactly that "out of the box".
5

How about this?

_.all(needed_permissions, function(v){
    return _.include(given_permissions, v);
});

Comments

2

Late answer but this works for me: _.isEqual(given_permissions, needed_permissions);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.