我有像这样的ruby哈希数组
string = "[{\"id\":13},{\"id\":15,\"children\":[{\"id\":16},{\"id\":17,\"children\":[{\"id\":19}]},{\"id\":18}]},{\"id\":14}]"
hash = Json.parse(string)
我正在尝试创建一个ruby哈希数组,如:
{13=>nil, 15=>nil, 16=>15, 17=>15, 19=>17, 18=>15, 14=>nil}
答案 0 :(得分:2)
这样做:
def build_hash(arr, hash={}, parent=nil)
return if arr.nil?
arr.each do |item|
hash[item['id']] = parent
build_hash(item['children'], hash, item['id'])
end
hash
end
build_hash(hash)
# => {13=>nil, 15=>nil, 16=>15, 17=>15, 19=>17, 18=>15, 14=>nil}
答案 1 :(得分:1)
我刚看到Uri发布他的解决方案,我刚刚完成了我的解决方案。我在一个数组上工作的哈希工作(你的输入实际上是一个哈希数组,而不是哈希)。否则它们大致相同。我喜欢他稍微好一点但是为了多样化:
@output = {}
def process(hash, parent=nil)
id = hash['id']
children = hash['children']
@output[id] = parent
children.each { |child| process(child, id) } unless children.nil?
end
hash.each { |h| process(h) }
p @output
# => {13=>nil, 15=>nil, 16=>15, 17=>15, 19=>17, 18=>15, 14=>nil}