简体   繁体   中英

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?

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

_.includes(myObject, x)

Checks if value is in collection.

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM