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.
Use array.Object. values(obj) make an array with the values of each key. Save this answer.
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.
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.
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With