是否有一種純粹的 Postgres 方法來轉換 JSONB 陣列,例如:
[{"id": 1, "name": "Dom" }, { "id": 2, "name": "Bass" }]
進入
{ 1: {"id": 1, "name": "Dom" }, 2: { "id": 2, "name": "Bass" } }
即與 Lodash 相同:
_.keyBy(arr, 'id)
uj5u.com熱心網友回復:
使用函式:
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)
$$;
在db<>fiddle 中測驗它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/313918.html
標籤:PostgreSQL jsonb
上一篇:PostgreSQL更新部分索引
