xanderUtin
xanderUtin

Reputation: 25

How to convert a string which is an array to an array using JavaScript

I am trying to store some array in .env files but when I access the particular value I got typeof string and I have use forEach to process my next step. in the .env file, email is stored like this

EMAILS = JSON.stringify(['[email protected]','[email protected]'])

I have used in this way also

EMAILS = ['[email protected]','[email protected]']

and in this way a

EMAILS = "['[email protected]','[email protected]']"

I want to make that array which is showing type of string into a normal array.

Upvotes: 0

Views: 64

Answers (1)

sdgluck
sdgluck

Reputation: 27347

It would be better not to store serialised JSON inside an .env file. Instead, store your "array" of items as a delimited list, for example using commas to separate the individual values. Like this:

# .env
[email protected],[email protected]
// javascript
const emails = env.EMAILS.split(",")

However, if you must store a serialised array, then you can parse it into JS by using JSON.parse:

# env
EMAILS=["[email protected]","[email protected]"]
// javascript
const emails = JSON.parse(env.EMAILS)

Upvotes: 1

Related Questions