[英]Generate a tree from string split
我有一个字符串数组
["ana_ola_una",
"ana_ola_ina",
"ana_asta",
"ana_ena_ola",
"ana_ena_cala",
"ana_ena_cina",
"ana_ena_cina_ula"]
我需要将其重新格式化为...的哈希值的哈希值,以使其成为树。 预期结果将是:
{ana:
{
ola: {
una: {},
ina: {}
},
asta: {},
ena: {
ola: {},
cala:{},
cina:
{
ula: {}
}
}
}
}
编辑:
我编辑此问题是因为我有一个相关的问题,最后我希望使用这种格式的JSON。 我该怎么办:
var tree = [
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
nodes: [
{
text: "Grandchild 1"
},
{
text: "Grandchild 2"
}
]
},
{
text: "Child 2"
}
]
},
{
text: "Parent 2"
},
{
text: "Parent 3"
},
{
text: "Parent 4"
},
{
text: "Parent 5"
}
];
arr = %w|ana_ola_una
ana_ola_ina
ana_asta
ana_ena_ola
ana_ena_cala
ana_ena_cina
ana_ena_cina_ula|
result = arr.each_with_object({}) do |s, memo|
s.split('_').inject(memo) do |deep, k|
deep[k.to_sym] ||= {}
end
end
mudasobwa的回答很好,但是如果您使用的是Ruby 2.3+,则这里有一个更为简洁的选择:
arr = [
"ana_ola_una",
"ana_ola_ina",
"ana_asta",
"ana_ena_ola",
"ana_ena_cala",
"ana_ena_cina",
"ana_ena_cina_ula"
]
tree = Hash.new {|h,k| h[k] = Hash.new(&h.default_proc) }
arr.each {|str| tree.dig(*str.split(?_).map(&:to_sym)) }
p tree
# => { ana:
# { ola:
# { una: {},
# ina: {}
# },
# asta: {},
# ena:
# { ola: {},
# cala: {},
# cina: { ula: {} }
# }
# }
# }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.