Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string with arrays to an array [duplicate]

How do I convert this piece of response into a valid array?
I want to perform an Object.map on the data:

var user_roles = "['store_owner', 'super_admin']";

This is not a valid JSON so I can't use JSON.parse

like image 254
ABEL MASILA Avatar asked Jul 18 '18 08:07

ABEL MASILA


People also ask

How do I convert a string to an array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


1 Answers

Right, most answers posted here suggest using JSON.parse and then get downvoted 3 times before getting deleted. What people overlook here is the lack of JSON-compliant quotation. The string IS, however, valid JavaScript. You can do the following:

const obj = {
  thing: "['store_owner', 'super_admin']",
  otherThing: "['apple', 'cookies']"
}

for (const key in obj) {
  const value = obj[key];
  obj[key] = eval(value);
}

console.log(obj);

Output will be a valid javascript object:

{"thing":["store_owner","super_admin"],"otherThing":["apple","cookies"]} 

Be careful with eval(), though! javascript eval() and security

You can try it here: https://es6console.com/jjqvrnhg/

like image 68
Berry M. Avatar answered Oct 19 '22 12:10

Berry M.