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

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

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

Resulting JSON:

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

See that last one, empty {} at the end. Therefore, at any time when the block is passed to array! returns nil , I get an empty element in the array, not the absence of an element. Is there an easy way to tell JBuilder not to output them? Or I just need to handle the output of array! like a simple ol 'array, and then compact or reject elements that I don't need?

+5
source share
2 answers

I think you can avoid your use case by first using reject for users, and just add 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 
+2
source

Perhaps you can try select instead of each , it will return a value only for elements other than nil

 json.array! @users.select do |user| unless user.address.nil? json.name user.name json.address user.address end end 
0
source

Source: https://habr.com/ru/post/1201258/


All Articles