javascript LoDash _.has 用于多个键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29001762/
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
LoDash _.has for multiple keys
提问by YarGnawh
Is there a method or a chain of methods to check if an array of keys exists in an object available in lodash, rather than using the following?
是否有一种方法或一系列方法来检查 lodash 中可用的对象中是否存在一组键,而不是使用以下方法?
var params = {...}
var isCompleteForm = true;
var requiredKeys = ['firstname', 'lastname', 'email']
for (var i in requiredKeys) {
if (_.has(params, requiredKeys[i]) == false) {
isCompleteForm = false;
break;
}
}
if (isCompleteForm) {
// do something fun
}
UPDATE
更新
Thanks everyone for the awesome solutions! If you're interested, here's the jsPerf of the different solutions.
感谢大家的真棒解决方案!如果您有兴趣,这里是不同解决方案的 jsPerf。
回答by Allan Baptista
I know the question is about lodash, but this can be done with vanilla JS, and it is much faster:
我知道问题是关于 lodash 的,但这可以用 vanilla JS 来完成,而且速度要快得多:
requiredKeys.every(function(k) { return k in params; })
and even cleaner in ES2015:
甚至在 ES2015 中更干净:
requiredKeys.every(k => k in params)
回答by thefourtheye
You can totally go functional, with every
, has
and partial
functions, like this
你可以完全去功能性,与every
,has
和partial
功能,这样
var requiredKeys = ['firstname', 'lastname', 'email'],
params = {
"firstname": "thefourtheye",
"lastname": "thefourtheye",
"email": "NONE"
};
console.log(_.every(requiredKeys, _.partial(_.has, params)));
// true
We pass a partial function object to _.every
, which is actually _.has
partially applied to params
object. _.every
will iterate requiredKeys
array and pass the current value to the partial object, which will apply the current value to the partial _.has
function and will return true
or false
. _.every
will return true
only if all the elements in the array returns true
when passed to the function object. In the example I have shown above, since all the keys are in params
, it returns true
. Even if a single element is not present in that, it will return false
.
我们将一个部分函数对象传递给_.every
,它实际上是_.has
部分应用于params
对象的。_.every
将迭代requiredKeys
数组并将当前值传递给部分对象,该对象会将当前值应用于部分_.has
函数并返回true
or false
。只有当数组中的所有元素在传递给函数对象时都返回时_.every
才会返回。在我上面显示的示例中,由于所有键都在 中,因此它返回. 即使其中不存在单个元素,它也会返回.true
true
params
true
false
回答by djechlin
_(requiredKeys).difference(_(params).keys().value()).empty()
I believe. The key step is getting everything into arrays then working with sets.
我相信。关键步骤是将所有内容放入数组,然后使用集合。
or
或者
_requiredKeys.map(_.pluck(params).bind(_)).compact().empty()
Might work.
可能工作。
回答by irysius
Assuming that params can have more properties than is required...
假设 params 可以具有比所需更多的属性......
var keys = _.keys(params);
var isCompleteForm = requiredKeys.every(function (key) {
return keys.indexOf(key) != -1;
});
Should do the trick.
应该做的伎俩。