根据值合并两个哈希数组的数据

时间:2013-05-20 19:32:18

标签: ruby arrays hash merge

我想加入两个数组。两个数组都包含具有共同单个键的哈希:object_id

data1 = [
  {"pid"=>"126199850741820_2172905", "object_id"=>606621809366286, "xcoord"=>81.885856079404, "ycoord"=>51.116625310174},
  {"pid"=>"126199850741820_2172905", "object_id"=>606621809366286, "xcoord"=>81.885856079404, "ycoord"=>51.116625310174}
]
data2 = [
  {"object_id"=>606621809366286, "name" => "123"},
  {"object_id"=>606621809366286, "name" => "321"}
]

我想基于匹配两个object_id来合并数据。数组data1的哈希值包含值为"object_id"的密钥"606621809366286"data2。我需要将这两个哈希值合并在一起,并输出一个新的哈希值,其中包含来自两个哈希值的其余部分的数据。

如果数据集中有其他键/值对不相同,则无关紧要。我只需匹配那些object_ids

3 个答案:

答案 0 :(得分:0)

require "pp"

data1 = [{"pid"=>"126199850741820_2172905", "object_id"=>606621809366286, "xcoord"=>81.885856079404, "ycoord"=>51.116625310174},{"pid"=>"126199850741820_2172905", "object_id"=>606621809366286, "xcoord"=>81.885856079404, "ycoord"=>51.116625310174}]
data2 = [{"object_id" => 606621809366286, "name" => "123"},{"object_id" => 606621809366286, "name" => "321"}]

pp data1.map{|h| data2.map{|i| h.merge(i) if i["object_id"]==h["object_id"]}.last}

输出:

[{"pid"=>"126199850741820_2172905",
  "object_id"=>606621809366286,
  "xcoord"=>81.885856079404,
  "ycoord"=>51.116625310174,
  "name"=>"321"},
 {"pid"=>"126199850741820_2172905",
  "object_id"=>606621809366286,
  "xcoord"=>81.885856079404,
  "ycoord"=>51.116625310174,
  "name"=>"321"}]

答案 1 :(得分:0)

我认为这就是你想要的:

merge = data1.dup
xref = {}
data2.each { |hash| xref[hash["object_id"]] = hash }
merge.each do |hash|
  oid = hash["object_id"]
  hash2 = xref[oid]
  if hash2
    hash2.each_pair do |kk, vv|
      next if "object_id" == kk
      hash[kk] = vv
    end
  end
end

使用您的数据运行此代码并发出:

pp merge

产生

[{"pid"=>"126199850741820_2172905",
  "object_id"=>606621809366286,
  "xcoord"=>81.885856079404,
  "ycoord"=>51.116625310174,
  "name"=>"321"},
 {"pid"=>"126199850741820_2172905",
  "object_id"=>606621809366286,
  "xcoord"=>81.885856079404,
  "ycoord"=>51.116625310174,
  "name"=>"321"}]

答案 2 :(得分:0)

我假设你的例子中所有四个具有相同ID的哈希都是一个错误,或者实际上是无关紧要的,你真正想要的是将data1中的每个哈希与data2中具有相同索引的哈希合并

这就是你想要的:

data1.zip(data2).map{|a| a[0].merge(a[1])}

输出:

[{"pid"=>"126199850741820_2172905",
  "object_id"=>606621809366286,
  "xcoord"=>81.885856079404,
  "ycoord"=>51.116625310174,
  "name"=>"123"},
 {"pid"=>"126199850741820_2172905",
  "object_id"=>606621809366286,
  "xcoord"=>81.885856079404,
  "ycoord"=>51.116625310174,
  "name"=>"321"}]