如何从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
相关产品推荐
相关产品推荐

