Reputation: 790
How to convert PostgreSQL Array in string eg. "{1,2,3,4}"
to javascript/typescript array: [1,2,3,4]
.
The values in the array must be a number type.
I tried a solution with replace and split but it returns string values.
var test = "{1,2,3,4}";
test = test.replace("{", "");
test = test.replace("}", "");
//test = test.replace(/\{|\}/gm, "") //regex replace
test.split(",") //['1', '2', '3', '4']
Upvotes: 3
Views: 4636
Reputation: 382102
A cleaner solution not involving building a JSON string just to parse it:
test = test.match(/[\w.-]+/g).map(Number)
But when dealing with a database you're usually not supposed to parse the data yourself unless you're writing the driver (but there are already good ones for postgresql).
Upvotes: 4
Reputation: 790
I find solution with JSON.parse but this also need replace before conversion.
var test = "{1,2,3,4}";
test = test.replace("{", "[");
test = test.replace("}", "]");
JSON.parse(test) //[1, 2, 3, 4]
Test with building a string for array size: 100000~900000: https://stackblitz.com/edit/typescript-gavnpg
Upvotes: 1