Ruby使用map重构嵌套数组对象时重复输出问题求助
Ruby哈希结构转换问题:重复对象与键名丢失修复
问题背景
需要将response中categorisedFeatures下每个对象的historical数组内的usageByMonth哈希结构,转换为{month: k, value: v}格式的对象数组。编写的代码运行后出现两个问题:
- 同一个
historical对象被重复输出多次 - 直接返回处理后的对象会丢失
PLATFORM这类顶级键名
原始代码
categorisedFeatures = response[:categorisedFeatures].map do |feature| newHistorical = (feature.dig(1, :historical)).map do |historical| usageByMonthRefactor = historical.dig(:usageByMonth)&.map { |(k, v)| { 'month': k, 'value': v } } newEntry = historical.merge({ usageByMonth: usageByMonthRefactor }) end newFeature = feature.dig(1).merge ({ historical: newHistorical }) feature&.map { |(k,v)| k=k , v=newFeature} end
问题分析
- 重复对象原因:
response[:categorisedFeatures]是哈希,调用map会返回由[键, 值]组成的数组。最后一行feature&.map { |(k,v)| k=k , v=newFeature}会把每个[键, 值]数组的两个元素都映射成[键, newFeature],导致每个feature生成两份重复数据。 - 键名丢失原因:直接返回
newFeature时,只保留了哈希的value部分,丢弃了原始的顶级键(如PLATFORM、CMS)。
修复后的代码
categorisedFeatures = response[:categorisedFeatures].transform_values do |feature_data| # 遍历并处理historical数组中的每个条目 updated_historical = feature_data[:historical].map do |historical_entry| # 将usageByMonth哈希转换为{month: k, value: v}格式的数组 refactored_usage = historical_entry[:usageByMonth]&.map { |month, value| { month: month, value: value } } # 合并更新后的usageByMonth到原条目 historical_entry.merge(usageByMonth: refactored_usage) end # 将更新后的historical数组合并回原feature数据 feature_data.merge(historical: updated_historical) end
代码解释
- 使用
transform_values方法:直接对哈希的每个value进行处理,同时保留原始的顶级键,完美解决键名丢失问题。 - 简化层级访问:
feature_data直接是categorisedFeatures中对应键的value哈希,无需用dig(1)去取值,代码更直观。 - 避免重复生成:每个
historical条目只被处理一次,map操作仅用于转换数组元素,不会额外生成重复数据。
内容的提问来源于stack exchange,提问作者Laura Gaxiola
相关产品推荐
相关产品推荐

