Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 940
AlexStack Avatar asked Mar 30 '15 13:03

AlexStack


People also ask

How do you check if all object keys has values?

Use array.Object. values(obj) make an array with the values of each key. Save this answer.

Is Lodash compatible with underscore?

Because Lodash is updated more frequently than Underscore. js, a lodash underscore build is provided to ensure compatibility with the latest stable version of Underscore.

How do you check if all object keys has false value?

To check if all of the values in an object are equal to false , use the Object. values() method to get an array of the object's values and call the every() method on the array, comparing each value to false and returning the result.


2 Answers

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.

like image 64
Gruff Bunny Avatar answered Oct 11 '22 23:10

Gruff Bunny


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 ...
like image 28
Calvin Cheng Avatar answered Oct 11 '22 23:10

Calvin Cheng