gpt4 book ai didi

ruby-on-rails - 如何在 Rails 中将数组对象转换为散列

转载 作者:数据小太阳 更新时间:2023-10-29 07:33:40 24 4
gpt4 key购买 nike

我有一个带有数组对象的散列:

{
false=>[#<Campaign id: 1, name: "campaign 1", active: false>, #<Campaign id: 3, name: "campaign 3", active: false>, #<Campaign id: 4, name: "campaign 4", active: false>],
true=>[#<Campaign id: 2, name: "campaign 2", active: true>]
}

如何将上面的hash转化为hash

{
false=>[{id:1, name:"campaign 1"}, {id:3, name: "capaign 3"}, ....],
true =>[{id:2, name:"campaign 2"}]
}

最佳答案

hash.each {|k,v| hash[k] = v.map{|e| {id: e[:id], name: e[:name]}}}

如果您可以使用select_all 方法获取散列数组,而不是对象数组,那么您就不需要将对象转换为散列。

ModelName.connection.select_all("select id, name from <table_name>;")
=> [{id:xxx, name: xxx}.......]

关于ruby-on-rails - 如何在 Rails 中将数组对象转换为散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33362994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com