lodash / underscore检查一个对象是否包含来自另一个对象的所有键/值

时间:2015-03-30 13:32:30

标签: javascript underscore.js lodash

这可能是一个简单的问题,但我无法从lodash API文档和Google中找到答案。

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

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

我想要一个可以传递键/值对的函数,如果该键存在于我的对象中且具有指定的值,则返回true:

_.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(),但仅限于一个对象。

3 个答案:

答案 0 :(得分:7)

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 ...

答案 1 :(得分:7)

您可以使用matcher

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

使用mixin:

_.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功能。

答案 2 :(得分:2)

我认为没有单一的下划线功能,但您可以轻松编写一个:

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