Converting an array in curly braces to a square bracketed array

五迷三道 提交于 2021-02-19 08:48:05

问题


I've inherited a database that stores an array of strings in the following format:

{"First","Second","Third","Fourth"}

This is output as an ordered list in the application. We're replacing the front-end mobile app at the moment (ionic / angular) and want to do an ngFor over this array. In the first iteration, we did a quick and dirty replace on the curly brackets and then split the string on "," but would like to use a better method.

What is the best method for treating this type of string as an array?


回答1:


You could do a string replacement of braces to brackets:

str.replace(/{(.*)}/, '[$1]')

This particular string could then be parsed as an array (via JSON.parse).




回答2:


If you're looking to do the parsing to an array on the front end, would this work?:

const oldStyle = '{"First","Second","Third","Fourth"}'

const parseOldStyleToArray = input => input
  .replace(/[\{\}]/g, '')
  .split(',')
  .map(item => item.replace(/\"/g, ''))
  

const result = parseOldStyleToArray(oldStyle)

console.dir(result)



回答3:


Another way to do more widest replacement by key:value mapping.

str = '{"First","Second","Third","Fourth"}';
mapping = {
  '{': '[',
  '}': ']'
}
result = str.replace(/[{}]/g, m => mapping[m]);
console.log(result);


来源:https://stackoverflow.com/questions/51711050/converting-an-array-in-curly-braces-to-a-square-bracketed-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!