15

有人对如何在咖啡脚本中查询哈希数组有指导吗?

例如,我有一个哈希数组,每个都有一个“名称”和“设置”:

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

我想在这个数组中找到哈希“名称”为“x_axis_label”的元素

我怎样才能用coffeescript轻松做到这一点?

我需要某种value_for_key_in_object(key, object)功能,并想知道是否会成为词典的一部分...

4

4 回答 4

32

我只是快速破解了这个:

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)

演示

于 2012-05-30T16:14:20.420 回答
12

如果您要反复执行此操作,总是寻找名称等于某物的东西,那么您最好将其从映射数组转换为键为名称的映射。

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'])

演示

于 2012-05-30T18:11:20.060 回答
10

我总是更喜欢“多语言”解决方案而不是“惯用”解决方案。因此你可以使用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
于 2014-06-03T09:07:52.937 回答
8

如果你碰巧在使用 Underscore.js,你可以使用find

xAxisLabel = _.find data, (datum) -> datum.name is 'x_axis_label'
于 2012-05-30T16:42:04.590 回答