user3565039
user3565039

Reputation: 185

Getting data from an array of hashes

Given the following array of hashes:

[{name: "joe", age: 21}, {name: "mary", age: 32}, {name: "mark", age: 25}]

How can I get an array of names returned, like this:

["joe","mary","mark"]

Upvotes: 0

Views: 67

Answers (3)

Ashish Kumar
Ashish Kumar

Reputation: 3039

I think map solves the problem.

[{name: "joe", age: 21}, {name: "mary", age: 32}, {name: "mark", age: 25}].map(function(node){return node.name});

// returns ["joe", "mary", "mark"]

Reference and fallback for .map()

Upvotes: -3

Uri Agassi
Uri Agassi

Reputation: 37409

using #map

arr = [{name: "joe", age: 21}, {name: "mary", age: 32}, {name: "mark", age: 25}]
arr.map { |x| x[:name] }
# => ["joe", "mary", "mark"] 

Upvotes: 4

Arup Rakshit
Arup Rakshit

Reputation: 118261

Just use Array#collect method

ary_of_hash = [{name: "joe", age: 21}, {name: "mary", age: 32}, {name: "mark", age: 25}]
ary_of_hash.collect { |hash| hash[:name] }

Upvotes: 2

Related Questions