1

I want to get a array of ids from my database table as a one-dimensional array.

I've used QueryArrayConfig for my query string with the rowMode set to "array". I get my ids correctly, but it returns a two-dimensional array.

            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]. 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.

0

1 Answer 1

1

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 . The default is to return each one as an object, so just remove the rowMode:"array" line and see if that works.

With the object you can use map or the array you can use a simple flatMap on your original results

let results = result.flatMap(row => row); // for the array or array results
let results = result.map(item => item.id); // for the object results
Sign up to request clarification or add additional context in comments.

2 Comments

If I remove rowMode: array, I get an array of javascript objects : [ anonymous { id: 1 }, anonymous { id: 2 } ]
Well it's either going to return an array of objects or an array of arrays, so it comes down to what you prefer working with

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.