简体   繁体   中英

How to group array of hashes by one key and merge inner keys and arrays

How can I transform an array of hashes:

[{
  id: 115,
  ref_id: 440000000000337,
  properties: [{name: "test"}],
  type: "content"
},{
  id: 116,
  ref_id: 440000000000337,
  properties: [{name: "asdf"}],
  type: "content"
}]

to get the desired result:

{
  id: 440000000000337
  type: "content"
  properties: [{name: "test"}, {name: "asdf"}]
}

in one block smarter then [sic] in the example? Would it be best to obtain this [sic] results with ruby functions?

in = _
out = {properties: []}
in.map {|i| out[:id] = i[:ref_id]; out[:properties] << i[:properties]; out[:type] = i[:type]}
out[:properties].flatten!

You cannot use the variable name in since it is a keyword. I will use iin instead.

out = {
  id: iin.last[:ref_id],
  type: iin.last[:type],
  properties: iin.flat_map{|e| e[:properties]}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM