如何将新密钥添加到json哈希数组中?

时间:2014-10-26 23:12:12

标签: ruby arrays json hash grouping

我有一个很大的数组:

[
{id: 1, name: 'abs', surname: 'abs'},
{id: 1, name: 'abs', surname: 'abs'},
...
{id: 1, name: 'abs', surname: 'abs'},
]

我需要添加新的'组'密钥到每个哈希。前五个哈希应该有'组:':1,后五个哈希应该有'组':2例如进入结果数组:

[
{id: 1, name: 'abs', surname: 'abs', group: 1},
{id: 1, name: 'abs', surname: 'abs', group: 1},
{id: 1, name: 'abs', surname: 'abs', group: 1},
{id: 1, name: 'abs', surname: 'abs', group: 1},
{id: 1, name: 'abs', surname: 'abs', group: 1},
{id: 1, name: 'abs', surname: 'abs', group: 2},
...
{id: 1, name: 'abs', surname: 'abs', group: N},
]

如果我使用Array#group_by和Array#each_with_index方法代码工作缓慢,导致数组有很多记录...我怎么能用ruby来让代码运行得更快?

2 个答案:

答案 0 :(得分:1)

我减少了您的输入样本,因为不需要那么大的样本。您可以通过此代码插入如何执行所需操作:

require 'json'

foo = [
  {id: 1, name: 'abs', surname: 'abs'},
  {id: 1, name: 'abs', surname: 'abs'},
  {id: 1, name: 'abs', surname: 'abs'},
  {id: 1, name: 'abs', surname: 'abs'},
]

foo.each_slice(2).with_index(1){ |a, i| a.each{ |h| h[:group] = i } }
puts foo.to_json
# >> [{"id":1,"name":"abs","surname":"abs","group":1},{"id":1,"name":"abs","surname":"abs","group":1},{"id":1,"name":"abs","surname":"abs","group":2},{"id":1,"name":"abs","surname":"abs","group":2}]

以下是看起来更具可读性的内容:

puts JSON::pretty_generate(foo)
# >> [
# >>   {
# >>     "id": 1,
# >>     "name": "abs",
# >>     "surname": "abs",
# >>     "group": 1
# >>   },
# >>   {
# >>     "id": 1,
# >>     "name": "abs",
# >>     "surname": "abs",
# >>     "group": 1
# >>   },
# >>   {
# >>     "id": 1,
# >>     "name": "abs",
# >>     "surname": "abs",
# >>     "group": 2
# >>   },
# >>   {
# >>     "id": 1,
# >>     "name": "abs",
# >>     "surname": "abs",
# >>     "group": 2
# >>   }
# >> ]

以下是发生的事情:

  • each_slice将数组切成N个大小的块。

    pp foo.each_slice(2).to_a
    # >> [[{:id=>1, :name=>"abs", :surname=>"abs", :group=>1},
    # >>   {:id=>1, :name=>"abs", :surname=>"abs", :group=>1}],
    # >>  [{:id=>1, :name=>"abs", :surname=>"abs", :group=>2},
    # >>   {:id=>1, :name=>"abs", :surname=>"abs", :group=>2}]]
    
  • with_index将增量值添加到传递给块的参数列表中。这被分配给块中的i

    pp foo.each_slice(2).with_index(1).to_a
    # >> [[[{:id=>1, :name=>"abs", :surname=>"abs", :group=>1},
    # >>    {:id=>1, :name=>"abs", :surname=>"abs", :group=>1}],
    # >>   1],
    # >>  [[{:id=>1, :name=>"abs", :surname=>"abs", :group=>2},
    # >>    {:id=>1, :name=>"abs", :surname=>"abs", :group=>2}],
    # >>   2]]
    

答案 1 :(得分:0)

怎么样:

foo = [
  {id: 1, name: 'abs', surname: 'abs'},
  {id: 1, name: 'abs', surname: 'abs'},
  {id: 1, name: 'abs', surname: 'abs'},
  {id: 1, name: 'abs', surname: 'abs'},
]
group_count =5

foo.each_with_index do |u,i|
  u['highlight_group'] = i.div( group_count ) 
end

puts foo