Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying an array of objects

Tags:

coffeescript

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...

like image 734
Daniel D Avatar asked May 30 '12 16:05

Daniel D


People also ask

How do I query an array of objects in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.

How do you query an array?

To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }

How do you filter an array of objects?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.


2 Answers

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

like image 39
Larry Maccherone Avatar answered Sep 24 '22 00:09

Larry Maccherone


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

like image 89
Rocket Hazmat Avatar answered Sep 25 '22 00:09

Rocket Hazmat