javascript 如果键与 underscore.js 匹配,则比较两个数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11755313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
compare two arrays if keys match with underscore.js
提问by Jareish
I have an array with permissions from Facebook and an array of the permissions that the user shouldve given:
我有一个来自 Facebook 的权限数组和一个用户应该给予的权限数组:
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.
现在我想以下划线精明的方式比较是否所有needed_permissions
都在given_permissions
, 中(无需自己循环两个数组并比较值)。我看到了一个_.include
方法,但它比较了一个数组和一个值。如果所有权限都可用,我想返回 true,否则返回 false。如果可能的话,我正在寻找一个不错的单线电话。
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.
这样做的原因是,FB.login
即使用户选择取消扩展权限,它也会返回 true。所以我需要仔细检查一下。
采纳答案by xiaowl
How about this?
这个怎么样?
_.all(needed_permissions, function(v){
return _.include(given_permissions, v);
});
回答by mu is too short
You could use _.difference
to see if removing the given permissions from your required permissions leaves anything behind:
您可以_.difference
用来查看从所需权限中删除给定权限是否会留下任何内容:
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.
这样做的一个很好的副作用是,diff
如果您想告诉他们出了什么问题,您将获得缺少的权限。
回答by vikeri
Late answer but this works for me: _.isEqual(given_permissions, needed_permissions);
迟到的答案,但这对我有用: _.isEqual(given_permissions, needed_permissions);