简体   繁体   中英

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

This is probably an easy question but I haven't been able to find an answer from the lodash API docs and Google.

Let's assume I have an object like this:

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

I want a function that I can pass a key/value pair and returns true if the key exists in my object and has the specified value:

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

This is somehow like where() but for only one object.

You could use a matcher :

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

with a 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

Edit

Version 1.8 of underscore added an _.isMatch function.

https://lodash.com/docs#has

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

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

My bad for misunderstanding your requirement at first.

Here's the corrected answer with _.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}) );

The trick is to cast the object you want to check as an Array so that _.some will do its magic.

If you want a nicer wrapper instead of having to manually cast it with [] , we can write a function that wraps the casting.

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

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

I don't think there is one single underscore function for that, but you can easily write one:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM