ruby on rails - Combine 2 Arrays with a single Dictionary -
i fetching 2 json arrays , storing them in variables called json_one , json_two. works fine, somehow combine them 1 single array.
how can combine 2 arrays single dictionary?
json_one
[ { "address": "1031 25th street san diego, ca 92102", "id": 1, "resource_type_id": 3, } ]
json_two
[ { "resource_id": 4, } [
i've tried this....
def show @user = user.find(params[:user_id]) @favorite = @user.favorites.find(params[:id]) @resource_data = [] (@resource_data << @favorite.resource_type.community_resources.where(:id => @favorite.resource_id)).flatten! (@resource_data << @favorite.resource_type.district_resources.where(:id => @favorite.resource_id)).flatten! (@resource_data << @favorite.resource_type.military_resources.where(:id => @favorite.resource_id)).flatten! (@resource_data << @favorite.resource_type.school_resources.where(:id => @favorite.resource_id)).flatten! @favorite_data = [] (@favorite_data << @favorite) json_one = @resource_data.to_json(:only => [:id, :resource_type_id,:district_id, :school_id, :name, :description, :website, :phone, :email, :address, :latitude, :longtude]) json_two = @favorite_data.to_json(:only => [:resource_id]) array1 = json.parse(json_one) array2 = json.parse(json_two) #array1 << array2 #firsts = array2.map {|array2| array2.first} combined = [ array1.first.merge(array2.first) ] respond_to |format| format.html format.json { render json: data } end end ###but result. ###i both dictionaries combined one. [ { "address": "1031 25th street san diego, ca 92102", "id": 1, "resource_type_id": 3, } { "resource_id": 4, } ]
json_one = "[{\"address\":\"1031 25th street san diego, ca 92102\",\"id\":1,\"resource_type_id\":3}]" json_two = "[{\"resource_id\":4}]" array1 = json.parse(json_one) array2 = json.parse(json_two) combined = [ array1.first.merge(array2.first) ] respond_to |format| format.html format.json { render json:combined } end
fwiw, without json:
combined = @resource_data.slice( :id, :resource_type_id,:district_id, :school_id, :name, :description, :website, :phone, :email, :address, :latitude, :longtude ) .merge( @favorite_data.slice( :resource_id ))
this pulls out desired attributes @resource_data
, , merges @favorite_data resource_id
attribute.
see rails slice docs.
Comments
Post a Comment