antonk antonk - 1 year ago 101
JSON Question

Jbuilder: How I can merge 2 top level arrays?

I have two top level arrays, which have the same format. And I want to merge them:

json = Jbuilder.encode do |json|
json.(companies) do |json, c|
json.value c.to_s
json.href employee_company_path(c)
json.(company_people) do |json, cp|
json.value "#{cp.to_s} (#{})"
json.href employee_company_path(

So the output would be as follows:
"[{value: "a", href: "/sample1"}, {value: "b", href: "/sample2"}]"

But the code above doesn't work. It includes only the second array:
"[{value: "b", href: "/sample2"}]"

Could someone help me? Thanks in advance.

Answer Source
result =  []
companies.each do |c|
  result << {:value => c.to_s, :href => employee_company_path(c)
company_people.each do |c|
  result << {:value => "#{cp.to_s} (#{})", :href => employee_company_path(
# at this point result will be an array of companies and people which just needs converting to json.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download