javascript - Use lodash to find a matching value if it exists -
i have following:
myarray = [{ "urltag": "google", "urltitle": "users", "status": 6, "nested": { "id": 2, "title": "http:\/\/www.google.com", } }, { "urltag": "bing", "tabtitle": "bingusers" }] i have myurltagtosearch = "yahoo", want loop through myarray, check if urltag equal "yahoo", if yes: return "yahoo", if not: return empty string (""). in example, should return "" because there "google" , "bing".
can lodash?
you can use lodash's find() method mixed regular conditional (if) statement this.
for starters, search array, can use:
var result = _.find(myarray, { "urltag": "yahoo" }); you can replace "yahoo" myurltagtosearch variable here.
if no matches found it'll return undefined, otherwise it'll return matching object. objects truthy values , undefined fasley value, can use result condition within if statement:
if (result) return "yahoo"; else return ""; we don't need define result here, can use:
if ( _.find(myarray, { "urltag": "yahoo" }) ) return "yahoo"; else return ""; or even:
return _.find(myarray, { "urltag": "yahoo" }) ? "yahoo" : "";
Comments
Post a Comment