如何将带有数组的字符串转换为数组 [英] How to convert a string with arrays to an array
问题描述
如何将此响应转换为有效数组?
我想执行 Object.map
关于数据:
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']";
这不是有效的JSON所以我不能使用 JSON.parse
This is not a valid JSON so I can't use JSON.parse
推荐答案
对,这里发布的大多数答案建议使用 JSON.parse
然后在被删除之前被投票3次。人们忽略了缺少符合JSON标准的报价。但是字符串IS是有效的JavaScript。您可以执行以下操作:
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);
输出将是一个有效的javascript对象:
Output will be a valid javascript object:
{"thing":["store_owner","super_admin"],"otherThing":["apple","cookies"]}
小心<$但是,c $ c> eval()! javascript eval()and security
您可以在此处尝试: https://es6console.com/jjqvrnhg/
这篇关于如何将带有数组的字符串转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!