Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to completely remove an empty element from an array with JBuilder

When using JBuilder, how I can completely remove evidence of an empty array element from my output? For this code sample, assume that we have three users and the third user has a nil address:

json.array! @users.each do |user|
  unless user.address.nil?
    json.name user.name
    json.address user.address
  end
end

The resulting JSON is:

[
  {
    "name":"Rob",
    "address":"123 Anywhere St."
  },
  {
    "name":"Jack",
    "address":"123 Anywhere St."
  },
  {}
]

See that last, empty {} at the end there. So any time the block passed to array! returns nil I end up with an empty element in the array, rather than a lack of element. Is there any easy way to tell JBuilder not to output those? Or do I just need to treat the output of array! as a plain ol' array and then compact or reject elements that I don't want?

like image 243
Rob Cameron Avatar asked Oct 31 '22 18:10

Rob Cameron


1 Answers

I think you can avoid your use case by first using reject on the users, and only add the valid users to the array:

json.array! @users.reject { |user| user.address.nil? }.each do |user|
  json.name user.name
  json.address user.address
end
like image 198
Uri Agassi Avatar answered Nov 14 '22 06:11

Uri Agassi