DareRelaqz
DareRelaqz

Reputation: 123

Converting a string of an array into an array in JS

I have a project I'm working on that implements MySQL, React and Express.js. I need to save an array into MySQL, but there are currently no ways to save an array, as far as I could see, so I was forced to convert it into a string. When I get it back from Express to the client, it's obviously a string, so I can't access the data. This array is used for a graph, mainly. What are some of the ways I can convert this string back to an array?

Upvotes: 3

Views: 4016

Answers (3)

Nils Kähler
Nils Kähler

Reputation: 3001

You can use JSON.parse() to convert a string into an array.

const response = "[1,2,3]";

console.log(JSON.parse(response));

Upvotes: 4

Raihanul
Raihanul

Reputation: 91

Depends on how you formed the string. If you used , for joining the elements, then you can use javascript's string.split() method.

let str = '1,2,3,4';
let arr = str.split(',');

Just pass in whatever delimiter you used to join the elements.

OR

If you're saving elements as a json string, then use JSON.parse(str) as shown by Nils Kähler in his answer

Upvotes: 1

Shubham Dixit
Shubham Dixit

Reputation: 1

You can store your json object (including arrays )in form of text in mysql database.What you have to do is JSON.stringify("your array") and persist it in database.And while you are retrieving it back from database you can JSON.parse() to get it in form of JavaScript object

Upvotes: 2

Related Questions