我寧願改變這種nasted array
到hash
更好馬平。
輸入
arr = [
{"__content__" => "Guitars", "id" => "2"},
{"__content__" => "For Guitars", "id" => "3", "parentId" => "2"},
{"__content__" => "6-string", "id" => "24", "parentId" => "2"},
{"__content__" => "7-string", "id" => "25", "parentId" => "2"},
{"__content__" => "8-string", "id" => "26", "parentId" => "2"}
]
創建父母
parents = arr.each_with_object({}) { |h, exp| exp[h['id']] = h['__content__'] }
這個好的地圖結構後,可以使用簡單的方法map
。
過程
output = arr.map do |h|
h['parentId'] = parents[h['parentId']] if h['parentId'] && parents[h['parentId']]
h
end
輸出
p output
# [
# {"__content__" => "Guitars", "id" => "2"},
# {"__content__" => "For Guitars", "id" => "3", "parentId" => "Guitars"},
# {"__content__" => "6-string", "id" => "24", "parentId" => "Guitars"},
# {"__content__" => "7-string", "id" => "25", "parentId" => "Guitars"},
# {"__content__" => "8-string", "id" => "26", "parentId" => "Guitars"}
# ]
我希望這有助於。
編輯
你也可以用這種方式
排序ID
arr.sort_by! { |h| h['id'] }
過程
output = arr.each_with_object({}) do |h, exp|
exp[h['id']] = h
h['parentId'] = exp[h['parentId']]['__content__'] if h['parentId'] && exp[h['parentId']]
h
end
在此之後,您將有ID散像鑰匙,讓你的輸出:
輸出
p output.values
# [
# {"__content__"=>"Guitars", "id"=>"2"},
# {"__content__"=>"6-string", "id"=>"24", "parentId"=>"Guitars"},
# {"__content__"=>"7-string", "id"=>"25", "parentId"=>"Guitars"},
# {"__content__"=>"8-string", "id"=>"26", "parentId"=>"Guitars"},
# {"__content__"=>"For Guitars", "id"=>"3", "parentId"=>"Guitars"}
# ]
那麼'__content__'的值需要放在'parentId'中嗎? – Roger