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?
source to share
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" : "";
source to share