简体   繁体   中英

Convert Array of Hashes to a Hash

I'm trying to convert the following:

dep = [
      {id: 1, depen: 2},
      {id: 1, depen: 3},
      {id: 3, depen: 4},
      {id: 5, depen: 3},
      {id: 3, depen: 6}
]

Into a single hash:

# {1=>2, 1=>3, 3=>4, 5=3, 3=>6}

I tried a solution I found on another question :

dep.each_with_object({}) { |g,h| h[g[:id]] = g[:dep_id] } 

However, the output removed elements and gave me:

#{1=>3, 3=>6, 5=>2}

where the last element is also incorrect.

You cannot have a hash like {1=>2, 1=>3, 3=>4, 5=3, 3=>6} . All keys of a hash mst have be unique.

If you want to get a hash mapping each id to a list of dependencies, you can use:

result = dep.
  group_by { |obj| obj[:id] }.
  transform_values { |objs| objs.map { |obj| obj[:depen] } }

Or

result = dep.reduce({}) do |memo, val|
  memo[val[:id]] ||= []
  memo[val[:id]].push val[:depen]
  memo
end

which produce

{1=>[2, 3], 3=>[4, 6], 5=>[3]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM