Home > Back-end >  Postgres JSONB function to key an array of objects, by a field
Postgres JSONB function to key an array of objects, by a field

Time:10-14

Is there a pure Postgres approach to turning a JSONB array like:

[{"id": 1, "name": "Dom" }, { "id": 2, "name": "Bass" }]

into

{ 1: {"id": 1, "name": "Dom" }, 2: { "id": 2, "name": "Bass" } }

I.e. same as Lodash doing:

_.keyBy(arr, 'id)

CodePudding user response:

Use the function:

create or replace function jsonb_key_by(jsonb, text)
returns jsonb language sql immutable as $$
    select jsonb_object_agg(elem->>$2, elem)
    from jsonb_array_elements($1) as arr(elem)
$$;

Test it in db<>fiddle.

  • Related