How can I do multiple _.has checks more elegantly?

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 the object property names match multiple lines.

The most intuitive way I've found is the following:

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

      

But if I have too many property names to validate, it becomes a pretty large piece of code.

I am trying to come up with a more elegant solution. I feel like it's almost okay, but I don't work (it always returns true). Here he is:

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

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

      

Can you tell me what is wrong? How to announce TestingValues

?

EDIT :

@Sergiu Paraschiv I used different values ​​in myObject

and test array just for ease of reading. Of course I tested it with the same values.

You are correct, I just figured it worked. I didn't at first because it doesn't work as intended. I have mixed things up: I want to return false if any element in the string array matches any attributesmyObject

+3


source to share


3 answers


You can do:

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

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

      



or, as you yourself suggested:

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

      

+3


source


Alternative:



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

      

0


source


You may 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);

      

0


source







All Articles