Reputation: 1199
I get the following array as JSON from an API when I call a country list:
{
"countries": [
[
"Andorra",
"AD"
],
[
"United Arab Emirates",
"AE"
],
[
"Afghanistan",
"AF"
],
[
"Antigua and Barbuda",
"AG"
],
[
"Anguilla",
"AI"
],
[
"Albania",
"AL"
],
[
"Armenia",
"AM"
]]}
This is my controller:
def find_countries
@countries = CountryStateSelect.countries_collection
render :json=>{ :countries=> @countries }
end
I want to separate this country list array like this.
{
"countries": [
[
value:"Andorra",
key: "AD"
],
[
value: "United Arab Emirates",
key:"AE"
],
[
value: "Afghanistan",
key:"AF"
],
[
value:"Antigua and Barbuda",
key:"AG"
]
]}
I cannot identify the value and the key. How can I separate this JSON response as above?
Upvotes: 0
Views: 498
Reputation: 30056
You need to map each item into an object
@countries = CountryStateSelect.countries_collection.map do |name, code|
Hash[:key, code, :value, name]
end
Upvotes: 5
Reputation: 286
Using collect method:
countries = CountryStateSelect.countries_collection.collect do |country, code|
{ key: code, value: country }
end
Upvotes: 1
Reputation: 121000
input = {
"countries": [
["Andorra", "AD"],
["United Arab Emirates", "AE"]
]
}
input.
transform_values do |vals|
vals.map(&%i[value key].method(:zip)).map(&:to_h)
end
#⇒ {
# :countries => [
# [0] {
# :key => "AD",
# :value => "Andorra"
# },
# [1] {
# :key => "AE",
# :value => "United Arab Emirates"
# }
# ]
# }
Upvotes: 1
Reputation: 11226
Just convert your arrays to hashes:
h = _ # your input data given
h[:countries].map!{|a| {value: a[0], key: a[1]} }
Upvotes: 1