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
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With