javascript 使用 lodash 查找匹配值(如果存在)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31386798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:43:33  来源:igfitidea点击:

Use lodash to find a matching value if it exists

javascriptlodash

提问by PhoonOne

I have the following:

我有以下几点:

 myArray = [{
        "urlTag": "Google",
        "urlTitle": "Users",
        "status": 6,
        "nested": {
            "id": 2,
            "title": "http:\/\/www.google.com",
        }
    },
    {
        "urlTag": "Bing",
        "tabTitle": "BingUsers"
    }]

I have myUrlTagToSearch = "Yahoo", I want to loop through myArray, check if any urlTagis equal to "Yahoo", if yes: return "Yahoo", if not: just return a empty string (""). In this example, it should return ""because there are only "Google"and "Bing".

我有myUrlTagToSearch = "Yahoo",我想循环myArray,检查是否有任何urlTag等于"Yahoo",如果是:返回"Yahoo",如果不是:只返回一个空字符串("")。在这个例子中,它应该返回,""因为只有"Google"and "Bing"

Can I do this with lodash?

我可以用 lodash 做到这一点吗?

回答by James Donnelly

You can use lodash's find()methodmixed with a regular conditional (if) statement to do this.

您可以将lodash 的find()方法与常规条件 ( if) 语句混合使用来执行此操作。

For starters, to search the array, you can use:

对于初学者,要搜索数组,您可以使用:

var result = _.find(myArray, { "urlTag": "Yahoo" });

You can replace "Yahoo"with your myUrlTagToSearchvariable here.

您可以在此处替换"Yahoo"为您的myUrlTagToSearch变量。

If no matches are found it'll return undefined, otherwise it'll return the matching Object. As Objects are truthyvalues and undefinedis a fasleyvalue, we can simply use resultas the condition within an ifstatement:

如果未找到匹配项,它将返回undefined,否则将返回匹配的Object。由于对象是值并且undefinedfasley值,我们可以简单地resultif语句中用作条件:

if (result)
    return "Yahoo";
else
    return "";


We don't even need to define resulthere, as we can simply use:

我们甚至不需要在result这里定义,因为我们可以简单地使用:

if ( _.find(myArray, { "urlTag": "Yahoo" }) )
    return "Yahoo";
else
    return "";

Or even:

甚至:

return _.find(myArray, { "urlTag": "Yahoo" }) ? "Yahoo" : "";

回答by Andy

You probably cando this with lodash (I don't know much about lodash), but in case no-one else answers there is a simple vanilla JS solution:

你可能可以用 lodash做到这一点(我对 lodash 不太了解),但如果没有其他人回答,有一个简单的 vanilla JS 解决方案:

function exists(site) {
    return myArray.some(function (el) {
      return el.urlTag === site;
    }) === false ? '': site;
}

exists('Yahoo');

DEMO

演示