Created
November 29, 2014 04:33
-
-
Save stephenhandley/61d7b215558a4aefd8ee to your computer and use it in GitHub Desktop.
finding object in array of objects by property value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| BARFS = [ | |
| { | |
| x : 10 | |
| name : 'pizza' | |
| } | |
| { | |
| x : 11 | |
| name : 'tacos' | |
| } | |
| { | |
| x : 12 | |
| name : 'burrito' | |
| } | |
| ] | |
| getBarfNamed = (name)-> | |
| for b in BARFS | |
| if (b.name is name) | |
| return b | |
| null | |
| getBarfNamedFilter = (name)-> | |
| matches = BARFS.filter((b)-> | |
| b.name is name | |
| ) | |
| if (matches.length > 0) | |
| matches[0] | |
| else | |
| null | |
| getBarfNamedDerp = (name)-> | |
| matches = (b for b in BARFS when b.name is name) | |
| if (matches.length > 0) | |
| matches[0] | |
| else | |
| null | |
| pizza = getBarfNamed('pizza') | |
| tacos = getBarfNamedFilter('tacos') | |
| burrito = getBarfNamedDerp('burrito') | |
| console.log("#{pizza.name}=#{pizza.x}") | |
| console.log("#{tacos.name}=#{tacos.x}") | |
| console.log("#{burrito.name}=#{burrito.x}") | |
| beer = getBarfNamed('beer') | |
| coke = getBarfNamedFilter('coke') | |
| gorp = getBarfNamedDerp('gorp') | |
| console.log(beer) | |
| console.log(coke) | |
| console.log(gorp) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment