Mauro74
Mauro74

Reputation: 4826

Lodash match string to object

I'm new to using Lodash so I apologise if the question is trivial.

I have a string and I have to validate it against a collection.

var x = 'foo'

var myObject = {
   one: 'bar',
   two: 'foo',
   three: 'wiz'
}

How do I compare the value of x against the value of one, two and three using Lodash (or plain JS if it's more convenient) to find if there's a match or not?

Upvotes: 2

Views: 3086

Answers (4)

Amir Popovich
Amir Popovich

Reputation: 29836

You can use Object.keys to get an object's keys and check if there is one or more keys in use by using Array.prototype.some:

var x = 'foo'

var myObject = {
   one: 'bar',
   two: 'foo',
   three: 'wiz'
}

var hasAnyKeyThatMatchesx = Object.keys(myObject).some(function(k){ return myObject[k] === x });

Upvotes: 1

Davin Tryon
Davin Tryon

Reputation: 67296

You can loop the properties of an object with for ... in (docs):

var x = 'foo';

var myObject = {
    one: 'bar',
    two: 'foo',
    three: 'wiz'
}

function containsValue(obj, value) {

    for (var prop in myObject) {
        if(x === myObject[prop]) {
            return true;
        }
    }
    return false;
}

console.log(containsValue(myObject, x));

This is just plain js.

Upvotes: 0

Cezary Daniel Nowak
Cezary Daniel Nowak

Reputation: 1174

find key by value _.findKey(myObject, (row) => row === x ) // returns "two"

just check if value exist: _.includes(myObject, x) // returns true

Upvotes: 0

Enver Dzhaparoff
Enver Dzhaparoff

Reputation: 4421

If you want to use Lodash for this example, you can use includes method:

_.includes(myObject, x)

Checks if value is in collection.

Upvotes: 4

Related Questions