Obtener datos de una matriz de 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"]

preguntado el 28 de mayo de 14 a las 14:05

3 Respuestas

usando #map

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

contestado el 28 de mayo de 14 a las 14:05

Sólo tiene que utilizar Array#collect Método

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

contestado el 28 de mayo de 14 a las 14:05

Creo que el mapa resuelve el problema.

[{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 para .map()

contestado el 28 de mayo de 14 a las 14:05

this is the way how we use map in JS. 'function' is argument for map function which accepts node as first arg here which refers the current element of the array while looping it. - Ashish Kumar

La pregunta está etiquetada ruby so answering with javascript is confusing, particularly when ruby has it's own map function with different syntax. - davidmangoose

oops... I dint see the tag - Ashish Kumar

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.