任何人都有关于如何在coffeescript中查询哈希数组的指导?
例如,我有一个哈希数组,每个哈希都有一个“名称”和“设置”:
[
{"name":"color", "setting":"red"},
{"name":"scale_min", "setting":"15"},
{"name":"scale_type", "setting":"linear"},
{"name":"x_axis_label", "setting":"Weeks"}
]
我想在这个数组中找到哈希“name”为“x_axis_label”的元素
如何使用coffeescript轻松完成?
我需要某种value_for_key_in_object(key, object)
函数,并想出它是否会成为词典的一部分......
答案 0 :(得分:30)
我很快就把它搞砸了:
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)
答案 1 :(得分:11)
如果您要反复执行此操作,请始终查找名称与某些内容相等的内容,那么您最好将其从一组地图转换为一个地图,其中键是名称。
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'])
答案 2 :(得分:9)
我总是喜欢多语言'解决一个惯用的问题'解。因此,您可以使用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
答案 3 :(得分:8)
如果您正在使用Underscore.js,则可以使用find
:
xAxisLabel = _.find data, (datum) -> datum.name is 'x_axis_label'