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?
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" : "";
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With