簡體   English   中英

如何通過一個鍵對哈希數組進行分組以及合並內部鍵和數組

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

如何轉換哈希數組:

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

得到期望的結果:

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

在示例中比[原文如此]聰明得多? 用ruby函數獲得此[sic]結果是否最好?

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

您不能在其中使用變量名稱in因為它是關鍵字。 我將使用iin代替。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM