TAGS :Viewed: 4 - Published at: a few seconds ago

[ How can I do more elegantly several _.has checks? ]

I have an object like this

myObject:{"property1": "valueX",
          "property2": "valueY",
          "property3": "valueZ",
          "property4": "valueV",
          "property5": "valueW"}

and I want to make sure that none of my object properties names match several strings.

The most intuitive way I found is this one:

if( !_.has(myObject, "TestingValue1")&&
    !_.has(myObject, "TestingValue2")&&
    !_.has(myObject, "TestingValue3")&&
    !_.has(myObject, "TestingValue4")){
//do something
}

But if I have too much property names to check, it is becoming quite a large piece of code.

I am trying to come up with a more elegant solution. I feel it is almost ok but I does not appear to work (it always returns true). Here it is:

var TestingValues = ["TestingValue1", "TestingValue2", "TestingValue3"]

if (!_.every(TestingValues, _.partial(_.has, myObject))){
//do something
}

Can you tell me what is wrong? How should I declare TestingValues?

EDIT:

@Sergiu Paraschiv I used different values in myObject and the test array only for making it easier to read. Of course I tested it with identical values.

You are right, I just realized it works. I didn't at first because it does not work as intended. I mixed things up: I want to return false if any of the item in the string array matches any of the attributes of myObject

Answer 1


You can do :

var TestingValues = [ "TestingValue1", "TestingValue2", "TestingValue3" ];

if(!_.isEmpty(_(myObject).pick(TestingValues)){...

or as you suggested yourself :

if (!_.some(TestingValues, _.partial(_.has, myObject)))

Answer 2


Alternative:

_some(TestValues, function(test) { return _.indexOf(_.values(myObject), test) != -1});

Answer 3


You can try

 var testingValues = ["TestingValue1", "TestingValue2", "TestingValue3"];

 var myObj = {
    "property1": "valueX",
    "property2": "valueY",
    "property3": "valueZ",
    "property4": "valueV",
    "property5": "valuez"
};

var result = _.every(myObj, function(value, key, obj){
    return !_.contains(testingValues, value);
});
console.log(result);