Let's assume I have a table users with a JSON column "foo". Values of that column look like this:
"{ field1: ['bar', 'bar2', 'bar3'], field2: ['baz', 'baz2', 'baz3'] }"

where field1 and field2 are optional, so column value may look like this: "{}"
I want to move values 'bar2' and 'bar3' from field1 to field2 for all records in this table.
Sample Output:
"{ field1: ['bar'], field2: ['baz', 'baz2', 'baz3', 'bar2', 'bar3']}"

More examples:
"{ field1: ['bar3'], field2: ['baz', 'baz2', 'baz3'] }"

should be transformed into
"{ field1: [], field2: ['baz', 'baz2', 'baz3', 'bar3'] }"

etc.
Is there any way to do this?
Unfortunately I have no idea how to approach this problem.

How can I move specific values from one field in a JSON column to another in PostgreSQL?
Using a series of subqueries with jsonb_array_elements
select jsonb_build_object('field1', coalesce((select jsonb_agg(v.value) 
       from jsonb_array_elements(u.foo -> 'field1') v 
       where v.value#>>'{}' not in ('bar2', 'bar3')), '[]'::jsonb),
   'field2', (u.foo -> 'field2') || (select jsonb_agg(v.value) 
       from jsonb_array_elements(u.foo -> 'field1') v 
       where v.value#>>'{}' in ('bar2', 'bar3'))) 
from users u 
where u.foo ? 'field1' and u.foo ? 'field2'

See fiddle
