You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从PostgreSQL查询结果快速构建指定格式的JS对象?

快速将查询结果转换为键值对象的方法

假设你的PostgreSQL查询返回的结果是一个包含对象的数组,示例结构如下:

const heroFollowData = [
  { superhero_id: 1, superhero_follow_count: 85 },
  { superhero_id: 2, superhero_follow_count: 42 },
  { superhero_id: 3, superhero_follow_count: 120 }
];

你可以用Array.reduce()一行代码完成转换,无需显式循环:

const followCountMap = heroFollowData.reduce((acc, item) => ({ ...acc, [item.superhero_id]: item.superhero_follow_count }), {});

如果追求更高性能(避免每次迭代展开对象),可以用更简洁的写法:

const followCountMap = heroFollowData.reduce((acc, item) => (acc[item.superhero_id] = item.superhero_follow_count, acc), {});

最终得到的followCountMap结构为:

{
  1: 85,
  2: 42,
  3: 120
}

内容的提问来源于stack exchange,提问作者Shaun Worcester

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 07:20:13