Billybobbonnet
Billybobbonnet

Reputation: 3226

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

Upvotes: 3

Views: 72

Answers (3)

Sami
Sami

Reputation: 4006

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

Upvotes: 0

Jeremy Thille
Jeremy Thille

Reputation: 26370

You can do :

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

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

or as you suggested yourself :

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

Upvotes: 3

Stephen Thomas
Stephen Thomas

Reputation: 14053

Alternative:

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

Upvotes: 0

Related Questions