lodash/underscore 检查一个对象是否包含另一个对象的所有 key/values

lodash/underscore check if one object contains all key/values from another object

这可能是一个简单的问题,但我无法从 lodash API 文档和 Google.

中找到答案

假设我有一个这样的对象:

var obj = {
  code: 2,
  persistence: true
}

我想要一个可以传递 key/value 对和 returns 如果键存在于我的对象中并具有指定值的函数:

_.XXXX(obj, {code: 2});  //true
_.XXXX(obj, {code: 3});  //false
_.XXXX(obj, {code: 2, persistence: false});  //false
_.XXXX(obj, {code: 2, persistence: true});   //true

这有点像 where() 但只有一个对象。

我不认为有一个单一的下划线函数,但你可以很容易地写一个:

function sameObject(ob1, ob2) {
   for (var key in ob2) {
      if (ob2[key] != ob1[key]) {
          return false;
      }
   }
   return true;
}

https://lodash.com/docs#has

var obj = {
  code: 2,
  persistence: true
};

console.log(_.has(obj, 'code'));

起初误解了您的要求,我很抱歉。

这是 _.some https://lodash.com/docs#some

的更正答案
var obj = {
  code: 2,
  persistence: true
};

console.log( _.some([obj], {code: 2}) );
console.log( _.some([obj], {code: 3}) );
console.log( _.some([obj], {code: 2, persistence: false}) );
console.log( _.some([obj], {code: 2, persistence: true}) );

诀窍是将要检查的对象转换为数组,以便 _.some 发挥其魔力。

如果你想要一个更好的包装器而不是必须用 [] 手动转换它,我们可以编写一个包装转换的函数。

var checkTruth = function(obj, keyValueCheck) {
  return _.some([obj], keyValueCheck);
};

console.log( checkTruth(obj, {code: 2}) );
... as above, just using the `checkTruth` function now ...

您可以使用 matcher:

var result1 = _.matcher({ code: 2 })( obj );  // returns true
var result2 = _.matcher({ code: 3 })( obj );  // returns false

使用混入:

_.mixin( { keyvaluematch: function(obj, test){
    return _.matcher(test)(obj);
}});

var result1 = _.keyvaluematch(obj, { code: 2 });  // returns true
var result2 = _.keyvaluematch(obj, { code: 3 });  // returns false

编辑

下划线 1.8 版添加了一个 _.isMatch 功能。