16

Anyone have guidance on how to query an array of hashes in coffeescript?

For example, I have an array of hashes, each with a "name" and "setting":

[
  {"name":"color", "setting":"red"},
  {"name":"scale_min", "setting":"15"},
  {"name":"scale_type", "setting":"linear"},
  {"name":"x_axis_label", "setting":"Weeks"}
]

I want to find the element in this array where the hash "name" is "x_axis_label"

How can I easily do that with coffeescript?

I need some kind of value_for_key_in_object(key, object) function and figured if would be part of the lexicon...

4 Answers 4

33

I just hacked this up quickly:

data = [{"name":"color","setting":"red"},{"name":"scale_min","setting":"15"},{"name":"scale_type","setting":"linear"},{"name":"x_axis_label","setting":"Weeks"}]

find = (i for i in data when i.name is 'x_axis_label')[0]

alert(find.setting)

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

That is awesome, and why I am really starting to love Coffeescript
12

If you going to do this repeatedly, always looking for things where the name equals something, then you are better off converting this from an array of maps to just a map where the key is the name.

data = [
  {"name":"color","setting":"red"}
  {"name":"scale_min","setting":"15"}
  {"name":"scale_type","setting":"linear"}
  {"name":"x_axis_label","setting":"Weeks"}
]

myMap = {}
for row in data
  myMap[row.name] = row.setting

alert(myMap['x_axis_label'])

Demo

Comments

10

I always prefer a 'multi language' solution over a 'idiomatic' solution. Thus you can to use Array.filter

data = [{"name":"color","setting":"red"},{"name":"scale_min","setting":"15"},{"name":"scale_type","setting":"linear"},{"name":"x_axis_label","setting":"Weeks"}]
find = (data.filter (i) -> i.name is 'x_axis_label')[0]
alert find.setting

Comments

8

If you happen to be using Underscore.js, you can use find:

xAxisLabel = _.find data, (datum) -> datum.name is 'x_axis_label'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.