Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stephenhandley/61d7b215558a4aefd8ee to your computer and use it in GitHub Desktop.
Save stephenhandley/61d7b215558a4aefd8ee to your computer and use it in GitHub Desktop.
finding object in array of objects by property value
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