Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert array_agg output to array and not string

I'm using array_agg to group values into an array. The output for row is:

row: anonymous { values: '{(1),(2)}' }

I'm trying to then loop through the results in Node,

row.values.forEach(... but it says values.forEach is not a function, because typeof row.values is String.

I'm using array_agg, so why is the output a string, and how can I convert it to an array?

like image 477
user3871 Avatar asked Jan 10 '17 18:01

user3871


1 Answers

I just ran into this problem too and unnest wasn't an option due to needing a fixed number of rows to be returned and I couldn't guarantee my content wouldn't contain a , or brackets which made a regex solution challenging.

I found the best solution was to use json_agg instead of array_agg. (See the documentation) This returned the results in JSON format and node automatically interpreted it as a javascript object so you can use .forEach without any conversion needed.

like image 106
Andrew McDowell Avatar answered Sep 18 '22 18:09

Andrew McDowell