简体   繁体   English

如何使用 javascript 将字符串字段数组转换回数组

[英]How to convert string field array back into an array with javascript

Im receiving from an API something like this我从 API 收到类似这样的东西

"['item1', 'item2', 'item3']"

so even though it looks like an array is actually a string.所以即使它看起来像一个数组实际上是一个字符串。 I want to convert that to an array again so I did this.我想再次将其转换为数组,所以我这样做了。

 let pseudoArray = "['item1', 'item2', 'item3']";
 let actualArray = pseudoArray.slice(1, -1).split(', ');

And it kinda works I just remove the brackets at the beginning and the end with slice() and use split to separate by the comma into an actual array.它有点工作我只是用slice()删除开头和结尾的括号,并使用split用逗号分隔成一个实际的数组。

But I feel this is not the best way to do it, is there a better, cleaner way to parse this string into an array?但我觉得这不是最好的方法,有没有更好、更干净的方法来将此字符串解析为数组?

I think the better approach would be replace all single quote with double quotes.我认为更好的方法是将所有单引号替换为双引号。

var items = "['item1', 'item2', 'item3']";
items = items.replace(/'/g, '"') //replacing all ' with "
console.log(JSON.parse(items))

Hope it helps!希望能帮助到你!

Just invert the characters ' and " to get the correct JSON string:只需反转字符'"以获得正确的 JSON 字符串:

 const str = "['item1', 'item2', 'item3']"; const mapping = {"'": '"', '"': "'"}; const jsonStr = str.replaceAll(/[\'\"]/g, (e) => mapping[e]); const arr = JSON.parse(jsonStr); console.log(arr);
 .as-console-wrapper { max-height: 100%;important: top: 0 }

You could try matching the string patterns directly, like this:您可以尝试直接匹配字符串模式,如下所示:

 var items = "['item1', 'item2', 'item3']"; const array = items.match(/(?<=')[^,].*?(?=')/g); console.log(array)

Best way is to first convert this normal string into a JSON string by replacing single quotes ( ' ) with double quotes ( " ) and then convert that JSON string into JSON object by using JSON.parse() method. Best way is to first convert this normal string into a JSON string by replacing single quotes ( ' ) with double quotes ( " ) and then convert that JSON string into JSON object by using JSON.parse() method.

Live Demo :现场演示

 let str = "['item1', 'item2', 'item3']"; str = str.replace(/'/g, '"'); console.log(JSON.parse(str));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM