我试图在关注json上调用uniq方法,以便它只返回employee_id上的唯一结果库
# Json array
a ={
results: [
{
employee: {
name: "A",
employee_id: "A-00016",
title: 1
}
},{
employee: {
name: "A",
employee_id: "A-00016",
title: 2
}
},{
employee: {
name: "C",
employee_id: "C-00017",
title: 3
}
}
]
}
# Calling uniq on a
a.uniq { |p| p.values_at(:employee_id) }
但是,我只得到这个结果
{
results: [
{
employee: {
name: "A",
employee_id: "A-00016",
title: 1
}
}
]
}
而不是我想要的
{
results: [
{
employee: {
name: "A",
employee_id: "A-00016",
title: 1
},{
employee: {
name: "C",
employee_id: "C-00017",
title: 3
}
}
]
}
我使用正确的方法输出我想要的结果吗?
答案 0 :(得分:3)
使用uniq
:
input[:results].uniq { |e| e[:employee][:employee_id] }
#⇒ [
# {:employee=>{:name=>"A", :employee_id=>"A-00016", :title=>"1"}},
# {:employee=>{:name=>"C", :employee_id=>"C-00017", :title=>"3"}}]
但我相信应该有一些条件适用于选择具有相同id
的兄弟姐妹的内容。下面的代码选择具有最大title
值的那个:
input[:results].group_by { |e| e[:employee][:employee_id] }
.map { |_, v| v.max_by { |e| e[:employee][:title].to_i } }
#⇒ [
# {:employee=>{:name=>"A", :employee_id=>"A-00016", :title=>"2"}},
# {:employee=>{:name=>"C", :employee_id=>"C-00017", :title=>"3"}}]
答案 1 :(得分:1)
以下是一种方法,为了返回修改后的输入hash
,我们可以使用uniq!
来修改数组a[:results]
。我们使用dup
复制哈希a
以保留它,然后使用tap
对重复哈希进行操作。
r = a.dup.tap do |h|
h[:results].uniq! do |h|
h[:employee][:employee_id]
end
end
#=> {:results=>
# [
# {:employee=>{:name=>"A", :employee_id=>"A-00016", :title=>1}},
# {:employee=>{:name=>"C", :employee_id=>"C-00017", :title=>3}}
# ]
# }
答案 2 :(得分:1)
def selection_criterion(h)
h[:title].to_i
end
{results: a[:results].group_by {|h| h[:employee][:employee_id]}.
values.
map {|arr| arr.max_by {|h| selection_criterion(h[:employee])}}}
#=> {:results=>
# [{:employee=>{:name=>"A", :employee_id=>"A-00016", :title=>2}},
# {:employee=>{:name=>"C", :employee_id=>"C-00017", :title=>3}}]}
根据需要定义selection_criterion
,并可能将max_by
更改为min_by
。
步骤如下。
b = a[:results]
# => [{:employee=>{:name=>"A", :employee_id=>"A-00016", :title=>1}},
# {:employee=>{:name=>"A", :employee_id=>"A-00016", :title=>2}},
# {:employee=>{:name=>"C", :employee_id=>"C-00017", :title=>3}}]
c = b.group_by { |h| h[:employee][:employee_id] }
#=> {"A-00016"=>[{:employee=>{:name=>"A", :employee_id=>"A-00016", :title=>1}},
# {:employee=>{:name=>"A", :employee_id=>"A-00016", :title=>2}}],
# "C-00017"=>[{:employee=>{:name=>"C", :employee_id=>"C-00017", :title=>3}}]}
d = c.values
#=> [[{:employee=>{:name=>"A", :employee_id=>"A-00016", :title=>1}},
# {:employee=>{:name=>"A", :employee_id=>"A-00016", :title=>2}}],
# [{:employee=>{:name=>"C", :employee_id=>"C-00017", :title=>3}}]]
e = d.map { |arr| arr.max_by { |h| selection_criterion(h[:employee]) } }
#=> [{:employee=>{:name=>"A", :employee_id=>"A-00016", :title=>2}},
# {:employee=>{:name=>"C", :employee_id=>"C-00017", :title=>3}}]
{ results: e }
#=> {:results=>
# [{:employee=>{:name=>"A", :employee_id=>"A-00016", :title=>2}},
# {:employee=>{:name=>"C", :employee_id=>"C-00017", :title=>3}}]}