Use lodash to find the matching value if it exists

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 go through myArray

, check if it makes a difference urlTag

"Yahoo"

, if yes: return "Yahoo"

, if not: just return an empty string (). In this example, it should return ""

because there is only "Google"

and "Bing"

.

Can I do this with lodash?

+3


source to share


2 answers


You can use lodash's methodfind()

mixed with regular conditional ( if

) for this.

First, to find an array, you can use:

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

      

You can replace "Yahoo"

with a variable here myUrlTagToSearch

.

If no matches are found it will return undefined

, otherwise it will return a matching one Object

. Since objects are true values ​​and undefined

are fasley values, we can simply use result

as a condition in the expression if

:

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

      




We don't even need to define here result

, as we can just use:

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

      

Or even:

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

      

+5


source


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

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

exists('Yahoo');

      



DEMO

0


source







All Articles