Obtener datos de una matriz de hashes
Frecuentes
Visto 62 equipos
0
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"]
3 Respuestas
4
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
2
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
-3
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
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas ruby ruby-on-rails-4 or haz tu propia pregunta.
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 ownmap
function with different syntax. - davidmangooseoops... I dint see the tag - Ashish Kumar