[英]Node-postgres - Flattening query result array
I want to get a array of ids from my database table as a one-dimensional array. 我想从数据库表中获取ID数组作为一维数组。
I've used QueryArrayConfig for my query string with the rowMode set to "array". 我已经将QueryArrayConfig用于查询字符串,并将rowMode设置为“ array”。 I get my ids correctly, but it returns a two-dimensional array.
我可以正确获取我的ID,但是它返回一个二维数组。
const idQuery: pg.QueryArrayConfig = {
name: 'get-ids',
text: 'SELECT id FROM MySchema.SomeTable'
rowMode: "array"
};
pool.query(idQuery).then((result: pg.QueryResult) => {
console.log(result.rows);
...
I get : [ [ 1 ], [ 2 ] ]
, but I need [1 , 2]
. 我得到:
[ [ 1 ], [ 2 ] ]
,但是我需要[1 , 2]
。 Is there a way to do this with my query directly?
有没有办法直接对我的查询执行此操作? Or do I need to flatten my array after I get my results?
还是在获得结果后需要展平阵列?
Edit : If I remove
rowMode: array
, I get an array of javascript objects : [anonymous { id: 1 }, anonymous { id: 2 }]
, which doesn't give me what I need. 编辑 :如果删除
rowMode: array
, rowMode: array
得到一个javascript对象数组: [anonymous { id: 1 }, anonymous { id: 2 }]
,这并不能满足我的需要。
If you use a rowMode
of 'Array' it will return each row as an individual array as per the docs https://node-postgres.com/features/queries#Query%20config%20object . 如果您使用'Array'的
rowMode
,则将按照docs https://node-postgres.com/features/queries#Query%20config%20object的形式将每一行作为单独的数组返回。 The default is to return each one as an object, so just remove the rowMode:"array"
line and see if that works. 默认值是将每个对象作为一个对象返回,因此只需删除
rowMode:"array"
行,看看是否rowMode:"array"
。
With the object you can use map
or the array you can use a simple flatMap
on your original results 使用对象,您可以使用
map
或数组,也可以在原始结果上使用简单的flatMap
let results = result.flatMap(row => row); // for the array or array results
let results = result.map(item => item.id); // for the object results
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.