Reputation: 26660
This is how to search for existence of value in array:
words = ["rattled", "roudy", "rebbles", "ranks"]
alert "Stop wagging me" if "ranks" in words
I am looking for similar elegance in searching for existence of object with specified property value:
words = [
{ id: 1, value: "rattled" },
{ id: 2, value: "roudy" },
{ id: 3, value: "rebbles" },
{ id: 4, value: "ranks" }
]
alert "Stop wagging me" if "ranks" in words.value
But the line at the bottom does not work.
Upvotes: 0
Views: 182
Reputation: 5374
If you want a 1-liner, you can do the following:
alert "Stop wagging me" if do -> return yes for w in words when w.value is 'ranks'
The advantage is that it will iterate in the array instead of deriving a new one (memory-efficient) and it will stop the iteration as soon as it finds a match (cpu-efficient). The price to pay is that it's perhaps a bit less readable. To address that, the best way might be to make your own utility function:
inObjectMember = (obj, key, value) ->
for o in obj when o[key] is value
return yes
alert "Stop wagging me" if inObjectMember words, 'value', 'ranks'
Upvotes: 1
Reputation: 40478
I just tried following and it worked for me:
alert "Stop wagging me" if "ranks" in (word.value for word in words)
Upvotes: 1