Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use lodash to find a 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 loop through myArray, check if any urlTag is 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".

Can I do this with lodash?

like image 548
PhoonOne Avatar asked Jan 08 '23 23:01

PhoonOne


2 Answers

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

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

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

You can replace "Yahoo" with your myUrlTagToSearch variable here.

If no matches are found it'll return undefined, otherwise it'll return the matching Object. As Objects are truthy values and undefined is a fasley value, we can simply use result as the condition within an if statement:

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

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

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

Or even:

return _.find(myArray, { "urlTag": "Yahoo" }) ? "Yahoo" : "";
like image 136
James Donnelly Avatar answered Jan 10 '23 13:01

James Donnelly


You probably can 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

like image 30
Andy Avatar answered Jan 10 '23 14:01

Andy