简体   繁体   English

Lodash将字符串与对象匹配

[英]Lodash match string to object

I'm new to using Lodash so I apologise if the question is trivial. 我是使用Lodash的新手,如果问题很简单,我深表歉意。

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? 如何使用Lodash(或更简单的JS)将x的值与onetwothree的值进行比较,以查找是否存在匹配项?

If you want to use Lodash for this example, you can use includes method: 如果要在此示例中使用Lodash ,则可以使用includes方法:

_.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 : 您可以使用Object.keys来获取对象的键,并通过使用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 ): 您可以for ... indocs )中使用for ... in循环对象的属性:

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. 这只是普通的js。

find key by value _.findKey(myObject, (row) => row === x ) // returns "two" 通过值_.findKey(myObject, (row) => row === x ) // returns "two"查找键_.findKey(myObject, (row) => row === x ) // returns "two"

just check if value exist: _.includes(myObject, x) // returns true 只需检查值是否存在: _.includes(myObject, x) // returns true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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