【问题标题】:Merge array of hash with same key合并具有相同键的哈希数组
【发布时间】:2018-02-12 17:25:16
【问题描述】:

我有一个哈希数组,如下所示。我想将某些字段的值与自定义分隔符合并。在这里,我只显示了数组中的两个哈希值,可能还有更多。但是,它们始终按照此处所示的相同顺序排列。

{
"details": [
{
  "place": "abc",
  "group": 3,
  "year": 2006,
  "id": 1304,
  "street": "xyz 14",
  "lf_number": "0118",
  "code": 4433,
  "name": "abc coorperation",
  "group2": 3817,
  "group1": 32,
  "postal_code": "22926",
  "status": 2
},
{
  "place": "cbc",
  "group": 2,
  "year": 2007,
  "id": 4983,
  "street": "mnc 14",
  "lf_number": "0145",
  "code": 4433,
  "name": "abc coorperation",
  "group2": 3817,
  "group1": 32,
  "postalcode": "22926",
  "status": 2
}
],
"@timestamp": "2017-09-04",
"parent": {
  "child": [
  {
    "w_2": 0.5,
    "w_1": 0.1,
    "id": 14226,
    "name": "air"
  },
  {
    "w_2": null,
    "w_1": 91,
    "id": 25002,
    "name": "Water"
  }]
},
"p_name": "anacin",
"@version": "1",
 "id": 28841
}

我想编辑详细信息。我想构建新的领域。

Field 1)  coorperations: (details.name | details.postal_code details.street ; details.name | details.postal_code details.street)

Output:
Coorperations: (abc coorperation |22926 xyz 14; abc coorperation | 22926 mnc 14)

Field 2) access_code: (details.status-details.id-details.group1-details.group2-details.group(always two digit)/details.year(only last two digits); details.status-details.id-details.group1-details.group2-details.group(always two digit)/details.year(only last two digits))

Output: access_code (2-32-3817-03-06; 2-32-3817-02-07)

我怎样才能为详细信息中的所有值实现这一点。这是最终结果的样子。

{
"@timestamp": "2017-09-04",
"parent": {
"child": [
 {
   "w_2": 0.5,
   "w_1": 0.1,
   "id": 14226,
   "name": "air"
  },
  {
   "w_2": null,
   "w_1": 91,
   "id": 25002,
   "name": "Water"
  }]
},
"p_name": "anacin",
"@version": "1",
"id": 28841,
"Coorperations" : "abc coorperation |22926 xyz 14; abc coorperation | 22926 mnc 14",
"access_code" : "2-32-3817-03-06; 2-32-3817-02-07"
}

【问题讨论】:

    标签: arrays json ruby hash


    【解决方案1】:

    您可以尝试在 Rails 控制台中运行此代码,哈希是您的 json:

    new_hash = hash.except(:details)
    coorperations = ""
    access_code = ""
    elements = hash[:details]
    elements.each do |element|
        coorperations = "#{coorperations}#{if coorperations.present? then '; ' else '' end}#{element[:name]} | #{element[:postal_code]} #{element[:street]}"
        access_code = "#{access_code}#{if access_code.present? then '; ' else '' end}#{element[:status]}-#{element[:id]}-#{element[:group1]}-#{element[:group2]}-#{element[:group1]}-#{element[:group]}"
    end
    new_hash.merge!(Coorperations: coorperations)
    new_hash.merge!(access_code: access_code)
    new_hash
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-03
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      • 2014-09-14
      • 2016-03-11
      • 1970-01-01
      • 2011-08-18
      相关资源
      最近更新 更多