-3

我想加入两个数组。两个数组都包含具有一个共同键的散列: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.

4

3 回答 3

1

我认为这就是你想要的:

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"}]
于 2013-05-20T19:56:39.587 回答
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"}]
于 2013-05-21T02:49:12.053 回答
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"}]
于 2013-05-20T19:49:31.860 回答